-- =========================================================
-- Migration 007: Legal Documents — Rechtliche Texte mit Versionierung
-- Consent/Vorlagen, Dokumentengenerator, Workflow
-- =========================================================

-- compliance_legal_documents: Rechtsdokument-Typen (DSE, AGB, Cookie etc.)
CREATE TABLE IF NOT EXISTS compliance_legal_documents (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(100),
    type VARCHAR(50) NOT NULL,       -- privacy_policy | terms | cookie_policy | imprint | dpa
    name VARCHAR(300) NOT NULL,
    description TEXT,
    mandatory BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- compliance_legal_document_versions: Versionierung mit Approval-Workflow
CREATE TABLE IF NOT EXISTS compliance_legal_document_versions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    document_id UUID NOT NULL REFERENCES compliance_legal_documents(id) ON DELETE CASCADE,
    version VARCHAR(20) NOT NULL,
    language VARCHAR(10) DEFAULT 'de',
    title VARCHAR(300) NOT NULL,
    content TEXT NOT NULL,
    summary TEXT,
    status VARCHAR(20) DEFAULT 'draft', -- draft|review|approved|published|archived|rejected
    created_by VARCHAR(200),
    approved_by VARCHAR(200),
    approved_at TIMESTAMPTZ,
    rejection_reason TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- compliance_legal_document_approvals: Audit-Trail fuer Freigaben
CREATE TABLE IF NOT EXISTS compliance_legal_document_approvals (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    version_id UUID NOT NULL REFERENCES compliance_legal_document_versions(id) ON DELETE CASCADE,
    action VARCHAR(50) NOT NULL,     -- submitted|approved|rejected|published|archived
    approver VARCHAR(200),
    comment TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Indizes
CREATE INDEX IF NOT EXISTS idx_legal_docs_tenant ON compliance_legal_documents(tenant_id);
CREATE INDEX IF NOT EXISTS idx_legal_docs_type ON compliance_legal_documents(type);
CREATE INDEX IF NOT EXISTS idx_legal_doc_versions_doc ON compliance_legal_document_versions(document_id);
CREATE INDEX IF NOT EXISTS idx_legal_doc_versions_status ON compliance_legal_document_versions(status);
CREATE INDEX IF NOT EXISTS idx_legal_doc_approvals_version ON compliance_legal_document_approvals(version_id);
