export class VendooApiError extends Error {
  constructor(message, { status = 0, code = 'API_ERROR', requestId = null, details = null } = {}) {
    super(message);
    this.name = 'VendooApiError';
    this.status = status;
    this.code = code;
    this.requestId = requestId;
    this.details = details;
  }
}

function readCookie(name) {
  const prefix = `${encodeURIComponent(name)}=`;
  return document.cookie.split(';').map(value => value.trim()).find(value => value.startsWith(prefix))?.slice(prefix.length) || '';
}

export async function apiRequest(path, { method = 'GET', body, headers = {}, signal } = {}) {
  const verb = String(method).toUpperCase();
  const requestHeaders = new Headers(headers);
  requestHeaders.set('Accept', 'application/json');
  if (body !== undefined) requestHeaders.set('Content-Type', 'application/json');
  if (!['GET', 'HEAD', 'OPTIONS'].includes(verb)) requestHeaders.set('X-CSRF-Token', decodeURIComponent(readCookie('csrf_token')));
  const response = await fetch(path, {
    method: verb,
    credentials: 'same-origin',
    headers: requestHeaders,
    body: body === undefined ? undefined : JSON.stringify(body),
    signal,
    redirect: 'error',
  });
  const requestId = response.headers.get('x-vendoo-request-id');
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) throw new VendooApiError(payload.error || `HTTP ${response.status}`, {
    status: response.status,
    code: payload.code || 'API_ERROR',
    requestId: payload.request_id || requestId,
    details: payload.details || null,
  });
  return payload;
}
