// cloud.jsx — Supabase cloud storage (zero-config for the user: keys entered in Admin).
// Uses the Supabase PostgREST REST API directly via fetch (runs in the visitor's browser).
//
// ONE table is required in the Supabase project — run this SQL once (instructions in Admin):
//   create table submissions (
//     id uuid primary key default gen_random_uuid(),
//     kind text, ref text, title text,
//     payload jsonb,
//     created_at timestamptz default now()
//   );
//   alter table submissions enable row level security;
//   create policy "public insert" on submissions for insert to anon with check (true);
//   create policy "public read"   on submissions for select to anon using (true);
//   create policy "public delete" on submissions for delete to anon using (true);

const CLOUD_CFG_KEY = 'ibtikar_cloud_cfg';

function cloudCfg() {
  try { return JSON.parse(localStorage.getItem(CLOUD_CFG_KEY) || 'null') || { url: '', key: '' }; }
  catch (e) { return { url: '', key: '' }; }
}
function setCloudCfg(cfg) {
  localStorage.setItem(CLOUD_CFG_KEY, JSON.stringify({ url: (cfg.url || '').trim().replace(/\/+$/, ''), key: (cfg.key || '').trim() }));
}
function cloudReady() {
  const c = cloudCfg();
  return !!(c.url && c.key);
}

function _headers(c, extra) {
  return Object.assign({
    'apikey': c.key,
    'Authorization': 'Bearer ' + c.key,
    'Content-Type': 'application/json',
  }, extra || {});
}

// insert one submission record (best-effort). Returns {ok, error}
async function cloudInsert(record) {
  const c = cloudCfg();
  if (!c.url || !c.key) return { ok: false, error: 'not-configured' };
  try {
    const row = { kind: record.kind || 'idea', ref: record.ref || '', title: record.title || '', payload: record };
    const res = await fetch(c.url + '/rest/v1/submissions', {
      method: 'POST',
      headers: _headers(c, { 'Prefer': 'return=minimal' }),
      body: JSON.stringify(row),
    });
    if (!res.ok) return { ok: false, error: 'HTTP ' + res.status + ' ' + (await res.text().catch(() => '')) };
    return { ok: true };
  } catch (e) { return { ok: false, error: String(e) }; }
}

// fetch all submissions (newest first). Returns {ok, rows:[payload...], error}
async function cloudFetch() {
  const c = cloudCfg();
  if (!c.url || !c.key) return { ok: false, error: 'not-configured', rows: [] };
  try {
    const res = await fetch(c.url + '/rest/v1/submissions?select=*&order=created_at.desc', { headers: _headers(c) });
    if (!res.ok) return { ok: false, error: 'HTTP ' + res.status, rows: [] };
    const data = await res.json();
    const rows = (data || []).map(r => Object.assign({}, r.payload, { _cloudId: r.id, savedAt: r.created_at ? Date.parse(r.created_at) : Date.now() }));
    return { ok: true, rows };
  } catch (e) { return { ok: false, error: String(e), rows: [] }; }
}

// delete by ref. Returns {ok, error}
async function cloudDelete(ref) {
  const c = cloudCfg();
  if (!c.url || !c.key) return { ok: false, error: 'not-configured' };
  try {
    const res = await fetch(c.url + '/rest/v1/submissions?ref=eq.' + encodeURIComponent(ref), {
      method: 'DELETE', headers: _headers(c, { 'Prefer': 'return=minimal' }),
    });
    return { ok: res.ok, error: res.ok ? null : 'HTTP ' + res.status };
  } catch (e) { return { ok: false, error: String(e) }; }
}

// test the connection. Returns {ok, error}
async function cloudTest() {
  const c = cloudCfg();
  if (!c.url || !c.key) return { ok: false, error: 'not-configured' };
  try {
    const res = await fetch(c.url + '/rest/v1/submissions?select=id&limit=1', { headers: _headers(c) });
    if (res.ok) return { ok: true };
    if (res.status === 404) return { ok: false, error: 'table-missing' };
    if (res.status === 401 || res.status === 403) return { ok: false, error: 'bad-key' };
    return { ok: false, error: 'HTTP ' + res.status };
  } catch (e) { return { ok: false, error: 'unreachable' }; }
}

Object.assign(window, { cloudCfg, setCloudCfg, cloudReady, cloudInsert, cloudFetch, cloudDelete, cloudTest, CLOUD_CFG_KEY });
