// Client API — toutes les requetes vers /api/*
// Auth : HTTP Basic, le navigateur mémorise les credentials apres premier prompt

const API_BASE = "/api";

async function apiCall(method, path, body) {
  const opts = {
    method,
    headers: { "Content-Type": "application/json" },
    credentials: "include",
  };
  if (body !== undefined) opts.body = JSON.stringify(body);
  const res = await fetch(`${API_BASE}${path}`, opts);
  if (res.status === 204) return null;
  if (!res.ok) {
    let detail = `HTTP ${res.status}`;
    try { const j = await res.json(); detail = j.detail || detail; } catch (e) {}
    throw new Error(detail);
  }
  return res.json();
}

const api = {
  // Recettes
  listRecettes: () => apiCall("GET", "/recettes"),
  getRecette:   (id) => apiCall("GET", `/recettes/${id}`),
  createRecette:(payload) => apiCall("POST", "/recettes", payload),
  updateRecette:(id, payload) => apiCall("PUT", `/recettes/${id}`, payload),
  deleteRecette:(id) => apiCall("DELETE", `/recettes/${id}`),

  // Baremes
  createBareme: (recetteId, payload) => apiCall("POST", `/recettes/${recetteId}/baremes`, payload),
  updateBareme: (id, payload) => apiCall("PUT", `/baremes/${id}`, payload),
  deleteBareme: (id) => apiCall("DELETE", `/baremes/${id}`),

  // Ingredients
  createIngredient: (baremeId, payload) => apiCall("POST", `/baremes/${baremeId}/ingredients`, payload),
  updateIngredient: (id, payload) => apiCall("PUT", `/ingredients/${id}`, payload),
  deleteIngredient: (id) => apiCall("DELETE", `/ingredients/${id}`),

  // Faconnages
  listFaconnages: () => apiCall("GET", "/faconnages"),
  createFaconnage: (payload) => apiCall("POST", "/faconnages", payload),
  updateFaconnage: (id, payload) => apiCall("PUT", `/faconnages/${id}`, payload),
  deleteFaconnage: (id) => apiCall("DELETE", `/faconnages/${id}`),

  // Incorporations
  listIncorporations: () => apiCall("GET", "/incorporations"),
  createIncorporation: (payload) => apiCall("POST", "/incorporations", payload),
  updateIncorporation: (id, payload) => apiCall("PUT", `/incorporations/${id}`, payload),
  deleteIncorporation: (id) => apiCall("DELETE", `/incorporations/${id}`),

  // Articles
  listArticles: () => apiCall("GET", "/articles"),
  updateMapping: (code, payload) => apiCall("PUT", `/articles/${code}/mapping`, payload),

  // Equipement
  listPetrins: () => apiCall("GET", "/petrins"),
  listDiviseuses: () => apiCall("GET", "/diviseuses"),

  // Snapshot
  snapshot: () => apiCall("GET", "/snapshot"),
};

window.api = api;
