-- Migration 150: Primaerzweck-Flag + MC <-> Quell-Regulierung (n:m)
-- Erweitert das Use-Case-Mapping um (a) is_primary (Primaerzweck pro MC)
-- und (b) mc_regulations (die feine Quell-Regulierungs-Filter-Dimension,
-- 117 Werte). 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='mc_use_case_mappings') THEN
    ALTER TABLE mc_use_case_mappings
        ADD COLUMN IF NOT EXISTS is_primary BOOLEAN NOT NULL DEFAULT FALSE;
    CREATE INDEX IF NOT EXISTS idx_mcuc_primary
        ON mc_use_case_mappings(use_case) WHERE is_primary;
  END IF;

  IF EXISTS (SELECT 1 FROM information_schema.tables
             WHERE table_schema='compliance'
               AND table_name='master_controls') THEN
    CREATE TABLE IF NOT EXISTS mc_regulations (
        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,
        source_regulation VARCHAR(160) NOT NULL,
        is_primary BOOLEAN NOT NULL DEFAULT FALSE,
        member_count INTEGER DEFAULT 0,
        method VARCHAR(20) NOT NULL DEFAULT 'lineage'
            CHECK (method IN ('lineage', 'manual')),
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        UNIQUE (master_control_uuid, source_regulation)
    );
    CREATE INDEX IF NOT EXISTS idx_mcreg_regulation
        ON mc_regulations(source_regulation);
    CREATE INDEX IF NOT EXISTS idx_mcreg_mc
        ON mc_regulations(master_control_uuid);
  END IF;
END $$;
