// Shared amerc API client. Same-origin /api on every *.amerc.ai subdomain
// (each nginx vhost proxies /api -> the backend; session cookie is Domain=.amerc.ai).
export const API = '/api';

export async function api(path, { method = 'GET', body, raw = false } = {}) {
  const res = await fetch(API + path, {
    method,
    headers: body ? { 'Content-Type': 'application/json' } : undefined,
    body: body ? JSON.stringify(body) : undefined,
    credentials: 'same-origin',
  });
  if (raw) return res;
  let data = {};
  try { data = await res.json(); } catch { /* ignore */ }
  if (!res.ok || data.ok === false) throw new Error(data.error || `request failed (${res.status})`);
  return data;
}

export const fileUrl = (id) => `${API}/files/${id}/raw`;

// Read a File object as base64 (for netdisk uploads).
export function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const r = new FileReader();
    r.onload = () => resolve(String(r.result).split(',')[1] || '');
    r.onerror = reject;
    r.readAsDataURL(file);
  });
}
