/** REST API calls. All functions return parsed JSON or throw on error. */

async function request(method, path, body) {
  const res = await fetch(path, {
    method,
    headers: body ? { 'Content-Type': 'application/json' } : {},
    body: body ? JSON.stringify(body) : undefined,
  });
  if (!res.ok && res.status !== 204) {
    const err = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(err.detail || res.statusText);
  }
  return res.status === 204 ? null : res.json();
}

export const api = {
  getProfiles:        ()               => request('GET',    '/agents/profiles'),
  getSessions:        ()               => request('GET',    '/sessions'),
  getSession:         (id)             => request('GET',    `/sessions/${id}`),
  createSession:      (profileId)      => request('POST',   '/sessions', { profile_id: profileId }),
  deleteSession:      (id)             => request('DELETE', `/sessions/${id}`),
  pinSession:         (id, pinned)     => request('PATCH',  `/sessions/${id}/pin`, { pinned }),
};
