/* Thin API client — all fetch calls go through here */

const API = {
  async _fetch(method, path, body) {
    const opts = { method, headers: { 'Content-Type': 'application/json' }, credentials: 'include' };
    // Add CSRF token header for state-changing methods
    if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(method)) {
      const name = 'bt_csrf_token';
      const match = document.cookie.match(new RegExp(name + '=([^;]+)'));
      if (match) opts.headers['x-csrf-token'] = match[1];
    }
    if (body !== undefined) opts.body = JSON.stringify(body);
    const res = await fetch('/api' + path, opts);
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
    return data;
  },

  get:    (path)       => API._fetch('GET',    path),
  post:   (path, body) => API._fetch('POST',   path, body),
  put:    (path, body) => API._fetch('PUT',    path, body),
  delete: (path)       => API._fetch('DELETE', path),

  // Tracker
  tracker: (year, month) => API.get(`/tracker?year=${year}&month=${month}`),

  // Bills
  bills:       ()      => API.get('/bills'),
  allBills:    ()      => API.get('/bills?inactive=true'),
  bill:        (id)    => API.get(`/bills/${id}`),
  createBill:  (data)  => API.post('/bills', data),
  updateBill:  (id, d) => API.put(`/bills/${id}`, d),
  deleteBill:  (id)    => API.delete(`/bills/${id}`),

  // Payments
  payments:       (billId, y, m) => API.get(`/payments?bill_id=${billId}&year=${y}&month=${m}`),
  quickPay:       (data)         => API.post('/payments/quick', data),
  createPayment:  (data)         => API.post('/payments', data),
  updatePayment:  (id, data)     => API.put(`/payments/${id}`, data),
  deletePayment:  (id)           => API.delete(`/payments/${id}`),

  // Categories
  categories:     ()      => API.get('/categories'),
  createCategory: (name)  => API.post('/categories', { name }),
  updateCategory: (id, n) => API.put(`/categories/${id}`, { name: n }),
  deleteCategory: (id)    => API.delete(`/categories/${id}`),

  // Settings
  settings:       ()      => API.get('/settings'),
  saveSettings:   (data)  => API.put('/settings', data),
};
