// Centrale API-client voor de Mek-Tech SPA.
// Alle calls gaan naar /api/spa (sessie-cookie via credentials: 'include').

const BASE = '/api/spa';

export class ApiError extends Error {
  constructor(message, status) {
    super(message);
    this.status = status;
  }
}

async function request(path, options = {}) {
  const res = await fetch(BASE + path, {
    credentials: 'include',
    headers: options.body ? { 'Content-Type': 'application/json' } : undefined,
    ...options,
    body: options.body ? JSON.stringify(options.body) : undefined
  });

  if (res.status === 401) {
    // Niet (meer) ingelogd — gooi event zodat de app naar login kan
    window.dispatchEvent(new Event('mek:unauthorized'));
    throw new ApiError('Niet ingelogd', 401);
  }

  let data = null;
  const text = await res.text();
  if (text) {
    try { data = JSON.parse(text); } catch { data = null; }
  }

  if (!res.ok) {
    throw new ApiError((data && data.error) || `Fout ${res.status}`, res.status);
  }
  return data;
}

export const api = {
  get: (path) => request(path),
  post: (path, body) => request(path, { method: 'POST', body }),
  put: (path, body) => request(path, { method: 'PUT', body }),
  del: (path) => request(path, { method: 'DELETE' })
};

// Helpers voor querystrings
export function qs(params) {
  const p = new URLSearchParams();
  for (const [k, v] of Object.entries(params || {})) {
    if (v !== undefined && v !== null && v !== '') p.set(k, v);
  }
  const s = p.toString();
  return s ? `?${s}` : '';
}

// Formatters (NL)
export const fmt = {
  euro: (n) => new Intl.NumberFormat('nl-NL', { style: 'currency', currency: 'EUR' }).format(n || 0),
  date: (d) => {
    if (!d) return '-';
    const dt = new Date(d);
    if (isNaN(dt)) return d;
    return dt.toLocaleDateString('nl-NL', { day: 'numeric', month: 'short', year: 'numeric' });
  },
  datetime: (d) => {
    if (!d) return '-';
    const dt = new Date(d);
    if (isNaN(dt)) return d;
    return dt.toLocaleDateString('nl-NL', { day: 'numeric', month: 'short' }) + ' ' + dt.toLocaleTimeString('nl-NL', { hour: '2-digit', minute: '2-digit' });
  },
  hours: (h) => `${(h || 0).toLocaleString('nl-NL', { maximumFractionDigits: 1 })}u`
};
