export function getApiConfig() {
  const apiUrl = localStorage.getItem('SSA_API_URL') || 'http://localhost/superbclientspayment/api';
  const apiKey = localStorage.getItem('SSA_API_KEY') || '';
  return { apiUrl: apiUrl.replace(/\/+$/, ''), apiKey };
}

async function request(path, options = {}) {
  const { apiUrl, apiKey } = getApiConfig();
  const url = apiUrl + path;

  const headers = new Headers(options.headers || {});
  headers.set('Content-Type', 'application/json');
  if (apiKey) headers.set('X-API-KEY', apiKey);

  const resp = await fetch(url, {
    ...options,
    headers,
  });

  const text = await resp.text();
  let data;
  try {
    data = text ? JSON.parse(text) : null;
  } catch {
    data = { error: text };
  }

  if (!resp.ok) {
    const msg = (data && data.error) ? data.error : `HTTP ${resp.status}`;
    throw new Error(msg);
  }

  return data;
}

export function apiGet(path) {
  return request(path, { method: 'GET' });
}

export function apiPost(path, body) {
  return request(path, { method: 'POST', body: JSON.stringify(body ?? {}) });
}

export function money(amount) {
  const n = Number(amount || 0);
  return n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

export function monthNow() {
  const d = new Date();
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  return `${y}-${m}`;
}
