-- Migration 034: TOM (Technisch-Organisatorische Massnahmen, Art. 32 DSGVO)
--
-- Two tables:
-- 1. compliance_tom_state: Persists the full TOM-Generator state per tenant (replaces In-Memory)
-- 2. compliance_tom_measures: Individual TOM measures (flat, queryable, for reports/export)

BEGIN;

-- ---------------------------------------------------------------------------
-- 1. TOM Generator State (one JSONB blob per tenant)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS compliance_tom_state (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(100) NOT NULL,
    state JSONB NOT NULL DEFAULT '{}',
    version INT NOT NULL DEFAULT 1,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(tenant_id)
);

CREATE INDEX IF NOT EXISTS idx_tom_state_tenant ON compliance_tom_state(tenant_id);

-- ---------------------------------------------------------------------------
-- 2. Individual TOM Measures (flat, queryable)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS compliance_tom_measures (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(100) NOT NULL,
    control_id VARCHAR(50) NOT NULL,
    name VARCHAR(300) NOT NULL,
    description TEXT,
    category VARCHAR(50) NOT NULL,
    type VARCHAR(20) NOT NULL,
    applicability VARCHAR(20) DEFAULT 'REQUIRED',
    applicability_reason TEXT,
    implementation_status VARCHAR(20) DEFAULT 'NOT_IMPLEMENTED',
    responsible_person VARCHAR(255),
    responsible_department VARCHAR(255),
    implementation_date TIMESTAMPTZ,
    review_date TIMESTAMPTZ,
    review_frequency VARCHAR(20),
    priority VARCHAR(20),
    complexity VARCHAR(20),
    linked_evidence JSONB DEFAULT '[]',
    evidence_gaps JSONB DEFAULT '[]',
    related_controls JSONB DEFAULT '{}',
    verified_at TIMESTAMPTZ,
    verified_by VARCHAR(200),
    effectiveness_rating VARCHAR(20),
    created_by VARCHAR(200) DEFAULT 'system',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(tenant_id, control_id)
);

CREATE INDEX IF NOT EXISTS idx_tom_measures_tenant ON compliance_tom_measures(tenant_id);
CREATE INDEX IF NOT EXISTS idx_tom_measures_category ON compliance_tom_measures(tenant_id, category);
CREATE INDEX IF NOT EXISTS idx_tom_measures_status ON compliance_tom_measures(tenant_id, implementation_status);

COMMIT;
