// Local fixture only. In a throwaway directory: npm install --save-exact @electric-sql/pglite@0.5.8
// Run this file with Node.js. No hosted service or credentials are used.
import { PGlite } from '@electric-sql/pglite';
import { writeFile } from 'node:fs/promises';
const db = new PGlite();
const query = `select c.relname as table_name, c.relrowsecurity as rls_enabled,
  has_table_privilege('anon', c.oid, 'SELECT') as anon_select_grant,
  has_table_privilege('authenticated', c.oid, 'SELECT') as authenticated_select_grant
from pg_class c
join pg_namespace n on n.oid = c.relnamespace
where n.nspname = 'public' and c.relkind in ('r', 'p')
order by c.relname;`;
await db.exec(`create role anon; create role authenticated;
create table public.notes (id int primary key, owner_id text not null, body text not null);
insert into public.notes values (1, 'A', 'TEST-A'), (2, 'B', 'TEST-B');
grant usage on schema public to anon, authenticated;
grant select on public.notes to anon, authenticated;`);
const snapshots = [];
async function readAs(role, id='') {
  await db.exec('begin');
  try {
    await db.exec(`set local role ${role};`);
    if (id) await db.query(`select set_config('app.test_user', $1, true)`,[id]);
    return (await db.query('select id from public.notes order by id')).rows.map(r=>r.id);
  } finally { await db.exec('rollback'); }
}
snapshots.push({state:'RLS off; SELECT granted',catalog:(await db.query(query)).rows,anon:await readAs('anon')});
await db.exec('alter table public.notes enable row level security;');
snapshots.push({state:'RLS on; no policies',catalog:(await db.query(query)).rows,anon:await readAs('anon'),authenticatedA:await readAs('authenticated','A')});
await db.exec(`create policy owner_read on public.notes for select to authenticated using (owner_id = current_setting('app.test_user', true));`);
snapshots.push({state:'RLS on; authenticated owner policy',catalog:(await db.query(query)).rows,anon:await readAs('anon'),authenticatedA:await readAs('authenticated','A'),authenticatedB:await readAs('authenticated','B')});
if (JSON.stringify(snapshots.map(s=>s.anon)) !== '[[1,2],[],[]]') throw Error('anon controls failed');
if (JSON.stringify(snapshots[2].authenticatedA) !== '[1]' || JSON.stringify(snapshots[2].authenticatedB) !== '[2]') throw Error('owner controls failed');
const result = {date:'2026-10-21',engine:'PGlite 0.5.8',scope:'Disposable local Postgres-compatible fixture only. app.test_user is a fixture identity setting, not Supabase Auth/JWT. No hosted Supabase, PostgREST, network or VibeRaven check was exercised. SELECT-grant flags are not proof that a caller can read any row.',query,snapshots};
await writeFile('rls-fixture-result.json',JSON.stringify(result,null,2)+'\n');
console.log(JSON.stringify(result,null,2));
await db.close();
