-- =========================================================
-- Migration 008: Einwilligungen — Consent-Tracking & Cookie-Banner
-- =========================================================

-- Tenant-Katalog: Welche Datenpunkte sind aktiv?
CREATE TABLE IF NOT EXISTS compliance_einwilligungen_catalog (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(100) NOT NULL UNIQUE,
    selected_data_point_ids JSONB DEFAULT '[]',
    custom_data_points JSONB DEFAULT '[]',
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Firmeninformationen fuer DSI-Generierung
CREATE TABLE IF NOT EXISTS compliance_einwilligungen_company (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(100) NOT NULL UNIQUE,
    data JSONB NOT NULL DEFAULT '{}',
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Cookie-Banner-Konfiguration (persistiert)
CREATE TABLE IF NOT EXISTS compliance_einwilligungen_cookies (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(100) NOT NULL UNIQUE,
    categories JSONB DEFAULT '[]',
    config JSONB DEFAULT '{}',
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Consent-Aufzeichnungen (Endnutzer-Einwilligungen)
CREATE TABLE IF NOT EXISTS compliance_einwilligungen_consents (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(100) NOT NULL,
    user_id VARCHAR(200) NOT NULL,
    data_point_id VARCHAR(100) NOT NULL,
    granted BOOLEAN NOT NULL DEFAULT TRUE,
    granted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    revoked_at TIMESTAMPTZ,
    ip_address VARCHAR(45),
    user_agent TEXT,
    consent_version VARCHAR(20) DEFAULT '1.0',
    source VARCHAR(100),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_einw_consents_tenant ON compliance_einwilligungen_consents(tenant_id);
CREATE INDEX IF NOT EXISTS idx_einw_consents_user ON compliance_einwilligungen_consents(tenant_id, user_id);
CREATE INDEX IF NOT EXISTS idx_einw_consents_dpid ON compliance_einwilligungen_consents(data_point_id);
CREATE INDEX IF NOT EXISTS idx_einw_catalog_tenant ON compliance_einwilligungen_catalog(tenant_id);
CREATE INDEX IF NOT EXISTS idx_einw_cookies_tenant ON compliance_einwilligungen_cookies(tenant_id);
