-- Migration 009: Consent History Tracking
-- Protokolliert alle Aenderungen an Einwilligungen (granted, revoked, version_update, renewed)
-- Wird automatisch bei POST /consents (granted) und PUT /consents/{id}/revoke (revoked) befuellt

SET search_path TO compliance, core, public;

CREATE TABLE IF NOT EXISTS compliance_einwilligungen_consent_history (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    consent_id      UUID NOT NULL,
    tenant_id       VARCHAR(100) NOT NULL,
    action          VARCHAR(50) NOT NULL,   -- granted | revoked | version_update | renewed
    consent_version VARCHAR(20),
    ip_address      VARCHAR(45),
    user_agent      TEXT,
    source          VARCHAR(100),
    created_at      TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_einw_history_consent ON compliance_einwilligungen_consent_history(consent_id);
CREATE INDEX IF NOT EXISTS idx_einw_history_tenant  ON compliance_einwilligungen_consent_history(tenant_id);
