// ============================================
// Reliq — Trust Registry API client (Launch Sprint L1)
// Thin fetch wrappers over the real backend registry endpoints.
// Local dev points directly at backend on http://127.0.0.1:3001.
// ============================================

const REGISTRY_BASE = 'https://api.reliq.dev/v1/registry';

async function _registryFetch(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(REGISTRY_BASE + path, opts);
  } catch (networkErr) {
    const err = new Error('Network error — could not reach the registry 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 || 'Registry API error');
    err.code = json.error?.code || 'REGISTRY_API_ERROR';
    err.status = res.status;
    throw err;
  }

  return json.data ?? json;
}

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

function _qs(params) {
  const parts = [];
  Object.keys(params || {}).forEach((k) => {
    const v = params[k];
    if (v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0)) return;
    parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(Array.isArray(v) ? v.join(',') : v)}`);
  });
  return parts.length ? `?${parts.join('&')}` : '';
}

const reliqRegistryApi = {
  discover(query) {
    return _registryFetch('GET', `/discover${_qs(query)}`);
  },

  discoverTop(query) {
    return _registryFetch('GET', `/discover/top${_qs(query)}`);
  },

  getProfile(slug) {
    return _registryFetch('GET', `/${encodeURIComponent(slug)}`);
  },

  getChanges(slug, limit) {
    return _registryFetch('GET', `/${encodeURIComponent(slug)}/changes${_qs({ limit })}`);
  },

  search(query) {
    return _registryFetch('GET', `/${_qs(query)}`);
  },

  publishProfile(input) {
    return _registryFetch('POST', '/profiles', { workspaceId: _wid(), ...input });
  },

  refreshProfile(slug) {
    return _registryFetch('POST', `/profiles/${encodeURIComponent(slug)}/refresh`, { workspaceId: _wid() });
  },

  enableMonitoring(slug, frequency) {
    return _registryFetch('POST', `/profiles/${encodeURIComponent(slug)}/monitoring/enable`, { workspaceId: _wid(), frequency });
  },

  disableMonitoring(slug) {
    return _registryFetch('POST', `/profiles/${encodeURIComponent(slug)}/monitoring/disable`, { workspaceId: _wid() });
  },

  updateMonitoring(slug, frequency) {
    return _registryFetch('PATCH', `/profiles/${encodeURIComponent(slug)}/monitoring`, { workspaceId: _wid(), frequency });
  },
};

Object.assign(window, { reliqRegistryApi });