-- Sprint 9 — Module Conformité RGPD / AI Act
-- E9-01: Processing registry (registre des traitements Art. 30 RGPD)

CREATE TABLE IF NOT EXISTS processing_registry (
    id                UUID        PRIMARY KEY DEFAULT uuid_generate_v4(),
    tenant_id         TEXT        NOT NULL,
    use_case_name     TEXT        NOT NULL,
    legal_basis       TEXT        NOT NULL
        CHECK (legal_basis IN (
            'consent', 'contract', 'legal_obligation',
            'vital_interests', 'public_task', 'legitimate_interest'
        )),
    purpose           TEXT        NOT NULL,
    data_categories   JSONB       NOT NULL DEFAULT '[]',
    recipients        JSONB       NOT NULL DEFAULT '[]',
    processors        JSONB       NOT NULL DEFAULT '[]',
    retention_period  TEXT        NOT NULL,
    security_measures TEXT,
    controller_name   TEXT,
    risk_level        TEXT        CHECK (risk_level IN ('minimal', 'limited', 'high', 'forbidden')),
    ai_act_answers    JSONB,
    is_active         BOOLEAN     NOT NULL DEFAULT TRUE,
    created_at        TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at        TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_processing_registry_tenant
    ON processing_registry (tenant_id, is_active);

-- E9-06: GDPR Art. 17 erasure audit log (immutable)
CREATE TABLE IF NOT EXISTS gdpr_erasure_log (
    id              UUID        PRIMARY KEY DEFAULT uuid_generate_v4(),
    tenant_id       TEXT        NOT NULL,
    target_user     TEXT        NOT NULL,
    requested_by    TEXT        NOT NULL,
    reason          TEXT,
    records_deleted INT         NOT NULL DEFAULT 0,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_erasure_log_tenant
    ON gdpr_erasure_log (tenant_id, target_user);
