-- Migration 149: MC <-> Use-Case Mappings (n:m) + Verifikations-Methode
-- Fundament fuer das Use-Case-Mapping-System: jede Master Control auf
-- >=1 Use Case (n:m) + genau eine Verifikations-Methode. Strikt add-only.
-- [migration-approved]

SET search_path TO compliance, public;

DO $$
BEGIN
  IF EXISTS (SELECT 1 FROM information_schema.tables
             WHERE table_schema = 'compliance'
               AND table_name = 'master_controls') THEN

    -- 1. n:m Mapping: Master Control -> Use Case
    CREATE TABLE IF NOT EXISTS mc_use_case_mappings (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        master_control_uuid UUID NOT NULL
            REFERENCES master_controls(id) ON DELETE CASCADE,
        master_control_id VARCHAR(60) NOT NULL,
        -- Registry-Key; KEIN SQL-CHECK -> neuer Use Case ohne Migration.
        -- Validierung erfolgt in der App gegen use_case_registry.
        use_case VARCHAR(40) NOT NULL,
        method VARCHAR(20) NOT NULL DEFAULT 'auto'
            CHECK (method IN ('auto', 'manual', 'seed')),
        confidence NUMERIC(3,2) DEFAULT 1.00
            CHECK (confidence >= 0 AND confidence <= 1),
        rationale TEXT,
        model VARCHAR(60),
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        UNIQUE (master_control_uuid, use_case)
    );
    CREATE INDEX IF NOT EXISTS idx_mcuc_use_case
        ON mc_use_case_mappings(use_case);
    CREATE INDEX IF NOT EXISTS idx_mcuc_uc_mc
        ON mc_use_case_mappings(use_case, master_control_uuid);

    -- 2. Verifikations-Methode pro MC (1 Zeile/MC)
    CREATE TABLE IF NOT EXISTS mc_verification (
        master_control_uuid UUID PRIMARY KEY
            REFERENCES master_controls(id) ON DELETE CASCADE,
        master_control_id VARCHAR(60) NOT NULL,
        verification_method VARCHAR(20) NOT NULL,   -- App-validiert
        method VARCHAR(20) NOT NULL DEFAULT 'auto'
            CHECK (method IN ('auto', 'manual', 'seed')),
        confidence NUMERIC(3,2) DEFAULT 1.00,
        rationale TEXT,
        updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
    );
    CREATE INDEX IF NOT EXISTS idx_mcv_method
        ON mc_verification(verification_method);

    -- 3. Sync-State: registry_hash -> Re-Klassifizierung bei Taxonomie-Aenderung
    CREATE TABLE IF NOT EXISTS mc_use_case_sync_state (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        registry_hash VARCHAR(64),
        stage VARCHAR(20),
        total_mappings INTEGER DEFAULT 0,
        mcs_classified INTEGER DEFAULT 0,
        last_run_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
    );

  END IF;
END $$;
