// config.jsx — Supabase project connection. The publishable key is safe in
// the browser (protected by RLS, not secrecy) — never put a secret/service
// key here. Must load AFTER the supabase-js CDN script and BEFORE store.jsx.
const HAVEN_SUPABASE_URL = 'https://oprsmhyvihrahxpfvdih.supabase.co';
const HAVEN_SUPABASE_ANON_KEY = 'sb_publishable_E385yKIPQ3z2NPru0-KTNA_lqVqW79h';
const HAVEN_SCHEMA = 'haven';

const Supa = window.supabase.createClient(HAVEN_SUPABASE_URL, HAVEN_SUPABASE_ANON_KEY);

// One schema-scoped client for table reads (`Db.from('claims').select()`) —
// RLS-gated to the caller's own org. All mutations go through `Rpc(...)`, not Db.
const Db = Supa.schema(HAVEN_SCHEMA);

/** Call a haven.* RPC. Throws with the Postgres error message on failure. */
async function Rpc(fn, args = {}) {
  const { data, error } = await Supa.schema(HAVEN_SCHEMA).rpc(fn, args);
  if (error) throw new Error(error.message || `${fn} failed`);
  return data;
}

const HAVEN_FUNCTIONS_BASE = `${HAVEN_SUPABASE_URL}/functions/v1`;

Object.assign(window, { Supa, Db, Rpc, HAVEN_FUNCTIONS_BASE, HAVEN_SCHEMA });
