-- =========================================================
-- Migration 006: VVT — Verzeichnis von Verarbeitungstaetigkeiten
-- Art. 30 DSGVO
-- =========================================================

CREATE TABLE IF NOT EXISTS compliance_vvt_organization (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    organization_name VARCHAR(300) NOT NULL,
    industry VARCHAR(100),
    locations JSONB DEFAULT '[]',
    employee_count INT,
    dpo_name VARCHAR(200),
    dpo_contact VARCHAR(200),
    vvt_version VARCHAR(20) DEFAULT '1.0',
    last_review_date DATE,
    next_review_date DATE,
    review_interval VARCHAR(20) DEFAULT 'annual',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ
);

CREATE TABLE IF NOT EXISTS compliance_vvt_activities (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    vvt_id VARCHAR(50) UNIQUE NOT NULL,
    name VARCHAR(300) NOT NULL,
    description TEXT,
    purposes JSONB DEFAULT '[]',
    legal_bases JSONB DEFAULT '[]',
    data_subject_categories JSONB DEFAULT '[]',
    personal_data_categories JSONB DEFAULT '[]',
    recipient_categories JSONB DEFAULT '[]',
    third_country_transfers JSONB DEFAULT '[]',
    retention_period JSONB DEFAULT '{}',
    tom_description TEXT,
    business_function VARCHAR(50),
    systems JSONB DEFAULT '[]',
    deployment_model VARCHAR(20),
    data_sources JSONB DEFAULT '[]',
    data_flows JSONB DEFAULT '[]',
    protection_level VARCHAR(10) DEFAULT 'MEDIUM',
    dpia_required BOOLEAN DEFAULT FALSE,
    structured_toms JSONB DEFAULT '{}',
    status VARCHAR(20) DEFAULT 'DRAFT',
    responsible VARCHAR(200),
    owner VARCHAR(200),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ
);

CREATE INDEX IF NOT EXISTS idx_vvt_activities_status ON compliance_vvt_activities(status);
CREATE INDEX IF NOT EXISTS idx_vvt_activities_business_function ON compliance_vvt_activities(business_function);
CREATE INDEX IF NOT EXISTS idx_vvt_activities_vvt_id ON compliance_vvt_activities(vvt_id);

CREATE TABLE IF NOT EXISTS compliance_vvt_audit_log (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    action VARCHAR(20) NOT NULL,
    entity_type VARCHAR(50) NOT NULL,
    entity_id UUID,
    changed_by VARCHAR(200),
    old_values JSONB,
    new_values JSONB,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_vvt_audit_created ON compliance_vvt_audit_log(created_at);
CREATE INDEX IF NOT EXISTS idx_vvt_audit_entity ON compliance_vvt_audit_log(entity_type, entity_id);
