-- =============================================================================
-- Migration 017: RAG Corpus Versioning
--
-- Tracks versions of the RAG corpus so assessments can record which
-- corpus version they were evaluated against. Enables staleness detection
-- and re-evaluation recommendations.
-- =============================================================================

CREATE TABLE IF NOT EXISTS compliance_corpus_versions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    version VARCHAR(50) NOT NULL,                  -- "2026-03-02.1"
    collection_name VARCHAR(100) NOT NULL,         -- "bp_compliance_ce"
    documents_count INT NOT NULL DEFAULT 0,
    chunks_count INT NOT NULL DEFAULT 0,
    regulations TEXT[],                            -- {"eu_2016_679", "eu_2024_1689"}
    digest VARCHAR(128),                           -- SHA256 over all chunks
    ingestion_source VARCHAR(200),                 -- "ingest-legal-corpus.sh"
    notes TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    created_by VARCHAR(100)
);

CREATE INDEX IF NOT EXISTS idx_corpus_versions_collection
    ON compliance_corpus_versions(collection_name);

CREATE INDEX IF NOT EXISTS idx_corpus_versions_latest
    ON compliance_corpus_versions(collection_name, created_at DESC);

-- Add corpus_version_id to ucca_assessments
ALTER TABLE ucca_assessments
    ADD COLUMN IF NOT EXISTS corpus_version_id UUID REFERENCES compliance_corpus_versions(id),
    ADD COLUMN IF NOT EXISTS corpus_version VARCHAR(50);

CREATE INDEX IF NOT EXISTS idx_ucca_assessments_corpus_version
    ON ucca_assessments(corpus_version_id);
