-- 0009_pro_anomaly_briefs.sql — Sun-Tzu's silent intermediate artefact.
--
-- The strategist produces one brief per topic. The case-writer pulls
-- the brief at narrative-assembly time and weaves the thesis + pillars
-- into a confident closing scene. The brief is NEVER surfaced reader-
-- facing — the table is internal to the runtime.
--
-- Apply as supabase_admin.

BEGIN;

CREATE SEQUENCE IF NOT EXISTS public.brief_id_seq START 1;

CREATE TABLE IF NOT EXISTS public.pro_anomaly_briefs (
  brief_pk         BIGSERIAL PRIMARY KEY,
  brief_id         TEXT UNIQUE NOT NULL,                 -- B-NNNN
  topic            TEXT NOT NULL,
  topic_pt_br      TEXT,
  doc_id           TEXT,                                 -- optional scope
  thesis           TEXT NOT NULL,
  thesis_pt_br     TEXT NOT NULL,
  pillars          JSONB NOT NULL,                       -- [{claim,claim_pt_br,support,support_pt_br}]
  unexplained      TEXT NOT NULL,
  unexplained_pt_br TEXT NOT NULL,
  created_by       TEXT NOT NULL DEFAULT 'strategist@detective',
  job_id           UUID,
  created_at       TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS pro_anomaly_briefs_topic_trgm
  ON public.pro_anomaly_briefs USING gin (topic gin_trgm_ops);

CREATE INDEX IF NOT EXISTS pro_anomaly_briefs_topic_pt_trgm
  ON public.pro_anomaly_briefs USING gin (topic_pt_br gin_trgm_ops);

CREATE INDEX IF NOT EXISTS pro_anomaly_briefs_doc_idx
  ON public.pro_anomaly_briefs (doc_id) WHERE doc_id IS NOT NULL;

-- Grants — investigator role (least privilege)
ALTER TABLE public.pro_anomaly_briefs ENABLE ROW LEVEL SECURITY;
GRANT SELECT, INSERT ON public.pro_anomaly_briefs TO investigator;
GRANT USAGE, SELECT, UPDATE ON SEQUENCE public.brief_id_seq            TO investigator;
GRANT USAGE, SELECT, UPDATE ON SEQUENCE public.pro_anomaly_briefs_brief_pk_seq TO investigator;

CREATE POLICY pro_anomaly_briefs_read   ON public.pro_anomaly_briefs FOR SELECT USING (true);
CREATE POLICY pro_anomaly_briefs_insert ON public.pro_anomaly_briefs FOR INSERT
  TO investigator, postgres, service_role WITH CHECK (true);

COMMIT;
