-- Migration 031: Service Module Registry Tables
-- Creates tables for compliance_service_modules, compliance_module_regulations,
-- and compliance_module_risks (aligned with SQLAlchemy models in db/models.py).

CREATE TABLE IF NOT EXISTS compliance_service_modules (
    id          TEXT PRIMARY KEY DEFAULT gen_random_uuid()::TEXT,
    name        TEXT NOT NULL UNIQUE,
    display_name TEXT NOT NULL,
    description TEXT,

    -- Technical details
    service_type        TEXT,
    port                INTEGER,
    technology_stack    JSONB DEFAULT '[]',
    repository_path     TEXT,
    docker_image        TEXT,

    -- Data categories
    data_categories         JSONB DEFAULT '[]',
    processes_pii           BOOLEAN DEFAULT FALSE,
    processes_health_data   BOOLEAN DEFAULT FALSE,
    ai_components           BOOLEAN DEFAULT FALSE,

    -- Status & compliance
    is_active               BOOLEAN DEFAULT TRUE,
    criticality             TEXT DEFAULT 'medium',
    compliance_score        FLOAT,
    last_compliance_check   TIMESTAMPTZ,

    -- Owner
    owner_team      TEXT,
    owner_contact   TEXT,

    -- Timestamps
    created_at  TIMESTAMPTZ DEFAULT NOW(),
    updated_at  TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS ix_module_type_active
    ON compliance_service_modules (service_type, is_active);

-- Regulation mappings (module → regulation with relevance level)
CREATE TABLE IF NOT EXISTS compliance_module_regulations (
    id              TEXT PRIMARY KEY DEFAULT gen_random_uuid()::TEXT,
    module_id       TEXT NOT NULL REFERENCES compliance_service_modules(id) ON DELETE CASCADE,
    regulation_id   TEXT NOT NULL REFERENCES compliance_regulations(id) ON DELETE CASCADE,

    relevance_level     TEXT NOT NULL DEFAULT 'medium',
    notes               TEXT,
    applicable_articles JSONB DEFAULT '[]',

    created_at  TIMESTAMPTZ DEFAULT NOW(),
    updated_at  TIMESTAMPTZ DEFAULT NOW(),

    CONSTRAINT uq_module_regulation UNIQUE (module_id, regulation_id)
);

CREATE INDEX IF NOT EXISTS ix_module_regulation_module
    ON compliance_module_regulations (module_id);

CREATE INDEX IF NOT EXISTS ix_module_regulation_regulation
    ON compliance_module_regulations (regulation_id);

-- Module risks (module → risk with module-specific assessment)
CREATE TABLE IF NOT EXISTS compliance_module_risks (
    id          TEXT PRIMARY KEY DEFAULT gen_random_uuid()::TEXT,
    module_id   TEXT NOT NULL REFERENCES compliance_service_modules(id) ON DELETE CASCADE,
    risk_id     TEXT NOT NULL REFERENCES compliance_risks(id) ON DELETE CASCADE,

    module_likelihood   INTEGER,
    module_impact       INTEGER,
    module_risk_level   TEXT,
    assessment_notes    TEXT,

    created_at  TIMESTAMPTZ DEFAULT NOW(),
    updated_at  TIMESTAMPTZ DEFAULT NOW(),

    CONSTRAINT uq_module_risk UNIQUE (module_id, risk_id)
);

CREATE INDEX IF NOT EXISTS ix_module_risk_module
    ON compliance_module_risks (module_id);
