/**
 * Thin API client — wraps fetch with the backend base URL.
 * Used from server-side load functions (hooks.server.js sets locals.api_url).
 */

/**
 * @param {string} baseUrl
 * @returns {ApiClient}
 */

/**
 * @typedef {Object} ApiClient
 * @property {(path: string) => Promise<any>} get
 * @property {(path: string, body: any) => Promise<any>} post
 */

export function apiClient(baseUrl) {
  async function request(path, options) {
    const resp = await fetch(`${baseUrl}${path}`, {
      ...options,
      headers: { 'Content-Type': 'application/json', ...options?.headers },
    });
    if (!resp.ok) {
      throw new Error(`API ${resp.status}: ${await resp.text()}`);
    }
    return resp.json();
  }
  return {
    get: (path) => request(path, { method: 'GET' }),
    post: (path, body) => request(path, { method: 'POST', body: JSON.stringify(body) }),
  };
}