/* Petit client HTTP pour l'API du serveur (même origine).
   Centralise fetch + gestion d'erreur + jeton admin. */

const apiRequest = async (method, path, { body, token } = {}) => {
  const headers = {};
  if (body !== undefined) headers["Content-Type"] = "application/json";
  if (token) headers["Authorization"] = `Bearer ${token}`;

  let res;
  try {
    res = await fetch(path, {
      method,
      headers,
      body: body !== undefined ? JSON.stringify(body) : undefined
    });
  } catch {
    // Serveur injoignable (hors ligne, coupure réseau…)
    const err = new Error("Serveur injoignable. Vérifie ta connexion.");
    err.offline = true;
    throw err;
  }

  if (res.status === 204) return null;

  let data = null;
  try { data = await res.json(); } catch { data = null; }

  if (!res.ok) {
    const err = new Error((data && data.error) || "Une erreur est survenue.");
    err.status = res.status;
    throw err;
  }
  return data;
};

const api = {
  get: (path, token) => apiRequest("GET", path, { token }),
  post: (path, body, token) => apiRequest("POST", path, { body, token }),
  put: (path, body, token) => apiRequest("PUT", path, { body, token }),
  del: (path, token) => apiRequest("DELETE", path, { token })
};

Object.assign(window, { api });
