// ============================================
// Reliq — Reports API client (Launch Sprint L1)
// Thin fetch wrappers over the real backend report endpoints.
// Local dev points directly at backend on http://127.0.0.1:3001.
// Exposed on window.reliqReportsApi.
// ============================================

const REPORTS_API_BASE = 'https://api.reliq.dev';

async function _reportsFetch(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(`${REPORTS_API_BASE}${path}`, opts);
  } catch (networkErr) {
    const err = new Error('Network error — could not reach the reports 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 || 'Reports API error');
    err.code = json.error?.code || 'REPORTS_API_ERROR';
    err.status = res.status;
    throw err;
  }

  return json.data ?? json;
}

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

const reliqReportsApi = {
  listReports() {
    return _reportsFetch('GET', `/v1/reports?workspaceId=${encodeURIComponent(_wid())}`);
  },

  getReport(reportId) {
    return _reportsFetch('GET', `/v1/reports/${encodeURIComponent(reportId)}?workspaceId=${encodeURIComponent(_wid())}`);
  },

  shareReport(reportId) {
    return _reportsFetch('POST', `/v1/reports/${encodeURIComponent(reportId)}/share`, { workspaceId: _wid() });
  },

  revokeShare(reportId) {
    return _reportsFetch('POST', `/v1/reports/${encodeURIComponent(reportId)}/share/revoke`, { workspaceId: _wid() });
  },

  getPublicReport(publicId) {
    return _reportsFetch('GET', `/v1/public/reports/${encodeURIComponent(publicId)}`);
  },

  getScan(scanId) {
    return _reportsFetch('GET', `/v1/scans/${encodeURIComponent(scanId)}?workspaceId=${encodeURIComponent(_wid())}`);
  },

  getScanFindings(scanId) {
    return _reportsFetch('GET', `/v1/scans/${encodeURIComponent(scanId)}/findings?workspaceId=${encodeURIComponent(_wid())}`);
  },
};

Object.assign(window, { reliqReportsApi });