// src/data/api.jsx — SPEC §10.1
// Thin backend HTTP client. Exposes window.API_BASE and window.apiFetch(path, opts).
// apiFetch sets Content-Type JSON, attaches Authorization when `auth` is supplied,
// parses the response body, and throws a tagged Error on non-2xx with the code
// from the backend's §7.2 error envelope.

window.API_BASE = window.API_BASE || "https://api.drgeorgefarah.com";

window.apiFetch = async (path, { method = "GET", body, auth, headers: extraHeaders } = {}) => {
  const headers = { "Content-Type": "application/json", ...(extraHeaders || {}) };
  if (auth) headers.Authorization = `Bearer ${auth}`;
  const res = await fetch(`${window.API_BASE}${path}`, {
    method,
    headers,
    body: body ? JSON.stringify(body) : undefined,
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok) {
    const err = new Error(json?.error?.message || res.statusText || "Request failed");
    err.code = json?.error?.code;
    err.status = res.status;
    err.details = json?.error?.details;
    err.requestId = json?.request_id;
    throw err;
  }
  return json;
};
