import type { AuthResult, Catalog, CrisisResource, DemoPersona, DialogEvent, Focus, MedsReference, Reply, Results, TodayPlan, } from "./types"; // Web: same-origin /api/v1 (Vite proxy in dev). Mobile shell: set VITE_API_BASE to the absolute API URL at build. const BASE: string = import.meta.env.VITE_API_BASE ?? "/api/v1"; export class ApiError extends Error { constructor( readonly status: number, message: string, ) { super(message); } } async function request(path: string, init?: RequestInit): Promise { let res: Response; try { res = await fetch(`${BASE}${path}`, { ...init, headers: { "Content-Type": "application/json", ...init?.headers }, }); } catch { throw new ApiError(0, "network"); } if (!res.ok) throw new ApiError(res.status, res.statusText); return (await res.json()) as T; } const post = (path: string, body?: unknown) => request(path, { method: "POST", body: body === undefined ? undefined : JSON.stringify(body) }); export const api = { signInEmias: (code: string) => post("/auth/emias", { code }), signInEmiasDemo: (personaToken: string) => post("/auth/emias/demo", { persona_token: personaToken }), signInAnonymous: (focus: Focus) => post("/auth/anonymous", { focus }), demoPersonas: () => request("/patient/demo-personas"), crisisResources: () => request("/crisis/resources"), catalog: () => request("/instruments/catalog"), medsReference: () => request("/meds/reference"), today: (token: string) => request(`/me/${encodeURIComponent(token)}/today`), results: (token: string) => request(`/me/${encodeURIComponent(token)}/results`), sendEvent: async (token: string, event: DialogEvent) => (await post<{ replies: Reply[] }>(`/dialog/${encodeURIComponent(token)}/events`, event)).replies, outbox: async (token: string) => (await request<{ replies: Reply[] }>(`/dialog/${encodeURIComponent(token)}/outbox`)).replies, };