-- 0006_investigator_serial_sequences.sql
--
-- BIGSERIAL on each investigation table created auto-sequences (e.g.
-- `evidence_evidence_pk_seq`) that 0004 forgot to GRANT to the investigator
-- role. Without those grants, every INSERT failed with:
--   permission denied for sequence evidence_evidence_pk_seq
--
-- Idempotent. Apply as supabase_admin.

BEGIN;

DO $$
DECLARE
  s TEXT;
BEGIN
  FOREACH s IN ARRAY ARRAY[
    'evidence_evidence_pk_seq',
    'hypotheses_hypothesis_pk_seq',
    'contradictions_contradiction_pk_seq',
    'witnesses_witness_pk_seq',
    'gaps_gap_pk_seq',
    'residual_uncertainties_ru_pk_seq'
  ]
  LOOP
    IF EXISTS (SELECT 1 FROM pg_class WHERE relname = s AND relkind = 'S') THEN
      EXECUTE format('GRANT USAGE, SELECT, UPDATE ON SEQUENCE public.%I TO investigator', s);
    END IF;
  END LOOP;
END
$$;

COMMIT;
