-- Migration 122: CRA Generated Documents
-- Tracks all auto-generated CRA documents (DoC, Technical Doc, CVD Policy, etc.)
-- with versioning so customers can audit-trail changes over time.

CREATE TABLE IF NOT EXISTS compliance_cra_documents (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    cra_project_id UUID NOT NULL,
    tenant_id VARCHAR(255) NOT NULL,

    -- Document classification
    doc_type VARCHAR(50) NOT NULL,
    -- doc_eu_conformity   -- EU DoC (Annex VII)
    -- doc_technical       -- Technische Doku (Annex V)
    -- doc_cvd_policy      -- Coordinated Vulnerability Disclosure Policy
    -- doc_update_policy   -- Update / Patch Policy
    -- doc_sbom_report     -- SBOM-Zusammenfassung

    -- Content (Markdown, can be converted to PDF later)
    title VARCHAR(500) NOT NULL,
    content_md TEXT NOT NULL,
    version INTEGER NOT NULL DEFAULT 1,

    -- Compliance metadata
    requirements_coverage JSONB DEFAULT '{}'::jsonb,  -- e.g. {covered: ["CRA-AI-23", ...], total: 40}
    generation_context JSONB DEFAULT '{}'::jsonb,     -- snapshot of project state at generation

    -- Signature/Approval (Phase 5 minimum: just status)
    status VARCHAR(20) NOT NULL DEFAULT 'draft',      -- draft | reviewed | approved | superseded
    signed_by VARCHAR(255),
    signed_at TIMESTAMPTZ,

    generated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    superseded_at TIMESTAMPTZ
);

CREATE INDEX IF NOT EXISTS idx_cra_docs_project ON compliance_cra_documents(cra_project_id);
CREATE INDEX IF NOT EXISTS idx_cra_docs_tenant ON compliance_cra_documents(tenant_id);
CREATE INDEX IF NOT EXISTS idx_cra_docs_type ON compliance_cra_documents(cra_project_id, doc_type, generated_at DESC);
CREATE INDEX IF NOT EXISTS idx_cra_docs_status ON compliance_cra_documents(cra_project_id, status);
