// ============================================
// Reliq — Billing API client
// Local dev points directly at backend on http://127.0.0.1:3001.
// ============================================

const BILLING_BASE = 'https://api.reliq.dev/v1/billing';

async function _billingFetch(method, path, body) {
  const opts = {
    method,
    credentials: 'include',
    headers: { 'Content-Type': 'application/json' },
  };

  if (body !== undefined) opts.body = JSON.stringify(body);

  let res;
  try {
    res = await fetch(BILLING_BASE + path, opts);
  } catch (networkErr) {
    const err = new Error('Network error — could not reach billing API.');
    err.code = 'NETWORK_ERROR';
    err.status = 0;
    throw err;
  }

  let json;
  try { json = await res.json(); } catch (_) { json = {}; }

  if (!res.ok) {
    const err = new Error(json.error?.message || 'Billing API error');
    err.code = json.error?.code || 'BILLING_API_ERROR';
    err.status = res.status;
    throw err;
  }

  return json.data ?? json;
}

function _wid() {
  try {
    return window.reliqWorkspace?.getWorkspace?.()?.id || '';
  } catch (_) {
    return '';
  }
}

const reliqBillingApi = {
  getBillingSummary() {
    return _billingFetch('GET', `/summary?workspaceId=${encodeURIComponent(_wid())}`);
  },

  getBillingPlans() {
    return _billingFetch('GET', '/plans');
  },

  startCheckout(planKey) {
    return _billingFetch('POST', '/checkout', { workspaceId: _wid(), planKey });
  },

  openBillingPortal() {
    return _billingFetch('POST', '/customer-portal', { workspaceId: _wid() });
  },

  changePlan(planKey) {
    return _billingFetch('POST', '/change-plan', { workspaceId: _wid(), planKey });
  },

  cancelSubscription() {
    return _billingFetch('POST', '/cancel', { workspaceId: _wid() });
  },

  reactivateSubscription() {
    return _billingFetch('POST', '/reactivate', { workspaceId: _wid() });
  },

  listInvoices() {
    return _billingFetch('GET', `/invoices?workspaceId=${encodeURIComponent(_wid())}`);
  },

  getInvoice(invoiceId) {
    return _billingFetch(
      'GET',
      `/invoices/${encodeURIComponent(invoiceId)}?workspaceId=${encodeURIComponent(_wid())}`,
    );
  },``
};

Object.assign(window, { reliqBillingApi });