// ─────────────────────────────────────────────────────
// API — fetch wrapper, mirrors public/js/auth.js authFetch()
// Bearer token from localStorage.crm_token; auto-logout on 401.
// ─────────────────────────────────────────────────────

const API = (() => {
  const TOKEN_KEY = 'crm_token';
  const USER_KEY  = 'crm_user';

  const getToken = () => localStorage.getItem(TOKEN_KEY);
  const getUser  = () => { try { return JSON.parse(localStorage.getItem(USER_KEY) || 'null'); } catch { return null; } };
  const setSession = (token, user) => {
    localStorage.setItem(TOKEN_KEY, token);
    localStorage.setItem(USER_KEY, JSON.stringify(user));
    window.dispatchEvent(new CustomEvent('erp:auth-changed'));
  };
  const clearSession = () => {
    localStorage.removeItem(TOKEN_KEY);
    localStorage.removeItem(USER_KEY);
    window.dispatchEvent(new CustomEvent('erp:auth-changed'));
  };

  async function request(path, opts = {}) {
    const headers = { ...(opts.headers || {}) };
    const token = getToken();
    if (token) headers['Authorization'] = `Bearer ${token}`;
    const isForm = opts.body instanceof FormData;
    if (!isForm && opts.body && typeof opts.body !== 'string') {
      headers['Content-Type'] = 'application/json';
      opts.body = JSON.stringify(opts.body);
    } else if (!isForm && !headers['Content-Type'] && opts.body) {
      headers['Content-Type'] = 'application/json';
    }
    const res = await fetch(path, { ...opts, headers });
    if (res.status === 401) {
      clearSession();
      throw new Error('UNAUTHORIZED');
    }
    return res;
  }

  async function json(path, opts = {}) {
    const res = await request(path, opts);
    const text = await res.text();
    const data = text ? JSON.parse(text) : null;
    if (!res.ok) {
      const err = new Error((data && data.error) || `HTTP ${res.status}`);
      err.status = res.status;
      err.data = data;
      throw err;
    }
    return data;
  }

  // GET helper with query params
  async function get(path, params) {
    const url = params ? `${path}${path.includes('?') ? '&' : '?'}${new URLSearchParams(params)}` : path;
    return json(url);
  }
  const post = (path, body)   => json(path, { method: 'POST',   body });
  const put = (path, body)    => json(path, { method: 'PUT',    body });
  const patch = (path, body)  => json(path, { method: 'PATCH',  body });
  const del = (path)          => json(path, { method: 'DELETE' });

  // Multipart upload (archivos, partes upload)
  async function upload(path, formData, opts = {}) {
    return json(path, { method: opts.method || 'POST', body: formData, ...opts });
  }

  // Blob download (exports → Excel/PDF)
  async function download(path, filename) {
    const res = await request(path);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const blob = await res.blob();
    const cd = res.headers.get('Content-Disposition') || '';
    const m = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(cd);
    const name = filename || (m && decodeURIComponent(m[1])) || 'download';
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = name;
    document.body.appendChild(a); a.click(); a.remove();
    URL.revokeObjectURL(url);
  }

  return { getToken, getUser, setSession, clearSession, request, json, get, post, put, patch, del, upload, download };
})();

window.API = API;
