// Tiny fetch wrapper. Reads token + investisseurId from localStorage.

const BASE = import.meta.env.VITE_API_URL || '/api';

function authHeaders() {
  const token = localStorage.getItem('cl_token');
  const investisseurId = localStorage.getItem('cl_investisseur_id');
  const h = {};
  if (token) h['Authorization'] = `Bearer ${token}`;
  if (investisseurId) h['X-Investisseur-Id'] = investisseurId;
  return h;
}

async function handle(res) {
  if (res.status === 204) return null;
  const text = await res.text();
  let body;
  try { body = text ? JSON.parse(text) : null; } catch { body = text; }
  if (!res.ok) {
    const msg = (body && body.error) || res.statusText || 'Request failed';
    const err = new Error(msg);
    err.status = res.status;
    err.details = body && body.details;
    throw err;
  }
  return body;
}

export const api = {
  get: (path, params) => {
    const qs = params ? '?' + new URLSearchParams(
      Object.entries(params).filter(([, v]) => v !== undefined && v !== null && v !== '')
    ).toString() : '';
    return fetch(BASE + path + qs, { headers: authHeaders() }).then(handle);
  },
  post: (path, body) =>
    fetch(BASE + path, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', ...authHeaders() },
      body: JSON.stringify(body),
    }).then(handle),
  put: (path, body) =>
    fetch(BASE + path, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json', ...authHeaders() },
      body: JSON.stringify(body),
    }).then(handle),
  patch: (path, body) =>
    fetch(BASE + path, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json', ...authHeaders() },
      body: JSON.stringify(body),
    }).then(handle),
  del: (path) =>
    fetch(BASE + path, { method: 'DELETE', headers: authHeaders() }).then(handle),
  upload: (path, formData) =>
    fetch(BASE + path, { method: 'POST', body: formData, headers: authHeaders() }).then(handle),
  blob: (path) =>
    fetch(BASE + path, { headers: authHeaders() }).then(async res => {
      if (!res.ok) { const t = await res.text(); throw new Error(t || res.statusText); }
      return res.blob();
    }),
  exportUrl: (path, params) => {
    const qs = params ? '?' + new URLSearchParams(params).toString() : '';
    return BASE + path + qs;
  },
};
