// Mini client REST : JSON, cookies de session, erreurs API normalisées.
import type { ApiError as ApiErrorBody } from '@arboretum/shared';

export class ApiError extends Error {
  constructor(
    readonly status: number,
    readonly code: string,
    message: string,
  ) {
    super(message);
    this.name = 'ApiError';
  }
}

async function request<T>(path: string, method: string, body?: unknown): Promise<T> {
  const init: RequestInit = { method, credentials: 'same-origin' };
  if (body !== undefined) {
    init.headers = { 'content-type': 'application/json' };
    init.body = JSON.stringify(body);
  }
  const res = await fetch(path, init);
  if (!res.ok) {
    let parsed: ApiErrorBody | null = null;
    try {
      parsed = (await res.json()) as ApiErrorBody;
    } catch {
      // réponse non-JSON : on retombe sur le statusText
    }
    throw new ApiError(res.status, parsed?.error.code ?? 'UNKNOWN', parsed?.error.message ?? res.statusText);
  }
  return (await res.json()) as T;
}

export const api = {
  get: <T>(path: string): Promise<T> => request<T>(path, 'GET'),
  post: <T>(path: string, body?: unknown): Promise<T> => request<T>(path, 'POST', body),
  patch: <T>(path: string, body?: unknown): Promise<T> => request<T>(path, 'PATCH', body),
  delete: <T>(path: string): Promise<T> => request<T>(path, 'DELETE'),
};
