// api.jsx — cliente da API Venda na Live
// Carregado depois de data.jsx (mock = fallback) e antes de app.jsx.
(function () {
  const API_BASE = new URL('api/', window.location.href).href.replace(/\/$/, '');

  async function req(path, opts) {
    const res = await fetch(API_BASE + path, Object.assign({
      headers: { 'Content-Type': 'application/json' },
    }, opts || {}));
    if (!res.ok) throw new Error('API ' + res.status + ' ' + path);
    return res.json();
  }

  window.API = {
    base: API_BASE,
    health: () => req('/health'),
    list: (resource) => req('/' + resource),
    get: (resource, id) => req('/' + resource + '/' + encodeURIComponent(id)),
    create: (resource, body) => req('/' + resource, { method: 'POST', body: JSON.stringify(body) }),
    update: (resource, id, body) => req('/' + resource + '/' + encodeURIComponent(id), { method: 'PUT', body: JSON.stringify(body) }),
    remove: (resource, id) => req('/' + resource + '/' + encodeURIComponent(id), { method: 'DELETE' }),
    async bootstrap() {
      const data = await req('/bootstrap');
      // Substitui os globais (mesmos nomes usados pelos módulos) pelos dados reais
      Object.keys(data).forEach((k) => {
        if (data[k] != null) window[k] = data[k];
      });
      window.__DATA_SOURCE = 'api';
      return data;
    },
  };
})();
