import type { LocationOption, SelectionState, UsageTemplate } from "./types"; const json = async (path: string): Promise => { const response = await fetch(path); if (!response.ok) { let details = ""; try { const payload = (await response.json()) as { message?: string }; details = payload.message ?? ""; } catch { // Ignore non-JSON error payloads. } throw new Error(details || `Request failed for ${path} (${response.status})`); } return (await response.json()) as T; }; export const api = { health: () => json<{ status: string; message?: string }>("/api/health"), locations: () => json("/api/locations"), publishers: (location: string) => json(`/api/publishers?location=${encodeURIComponent(location)}`), offers: (location: string, publisher: string) => json(`/api/offers?location=${encodeURIComponent(location)}&publisher=${encodeURIComponent(publisher)}`), skus: (location: string, publisher: string, offer: string) => json( `/api/skus?location=${encodeURIComponent(location)}&publisher=${encodeURIComponent(publisher)}&offer=${encodeURIComponent(offer)}` ), versions: (location: string, publisher: string, offer: string, sku: string) => json( `/api/versions?location=${encodeURIComponent(location)}&publisher=${encodeURIComponent(publisher)}&offer=${encodeURIComponent(offer)}&sku=${encodeURIComponent(sku)}` ), templates: () => json("/api/templates"), render: async (templateFile: string, selection: SelectionState): Promise => { const response = await fetch("/api/render", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ templateFile, selection }) }); if (!response.ok) { throw new Error("Failed to render template"); } const payload = (await response.json()) as { rendered: string }; return payload.rendered; }, skuExport: async (location: string, publisher: string, offer: string): Promise => { const payload = await json<{ rendered: string }>( `/api/sku-export?location=${encodeURIComponent(location)}&publisher=${encodeURIComponent(publisher)}&offer=${encodeURIComponent(offer)}` ); return payload.rendered; } };