-- Migration 026: Hierarchische Kontext-Zuordnung Reifegradmodell → Fokus / Stilrichtung / Trainingsstil
-- Vererbung: Modell auf Fokus-Ebene gilt als Basis; spezifischere Zeilen überschreiben Zelltexte
--            für dieselbe Fähigkeit (skill_id) beim Zusammenführen (resolve).
-- Datum: 2026-04-27

CREATE TABLE IF NOT EXISTS maturity_model_context_bindings (
    id SERIAL PRIMARY KEY,
    maturity_model_id INT NOT NULL REFERENCES maturity_models(id) ON DELETE CASCADE,
    focus_area_id       INT NOT NULL REFERENCES focus_areas(id) ON DELETE CASCADE,
    style_direction_id  INT REFERENCES style_directions(id) ON DELETE CASCADE,
    training_type_id    INT REFERENCES training_types(id) ON DELETE CASCADE,
    created_at          TIMESTAMP DEFAULT NOW(),
    updated_at          TIMESTAMP DEFAULT NOW(),
    CONSTRAINT chk_mcb_tier CHECK (
        (style_direction_id IS NULL AND training_type_id IS NULL)
        OR (style_direction_id IS NOT NULL AND training_type_id IS NULL)
        OR (style_direction_id IS NOT NULL AND training_type_id IS NOT NULL)
    )
);

CREATE INDEX IF NOT EXISTS idx_mmcb_model ON maturity_model_context_bindings(maturity_model_id);
CREATE INDEX IF NOT EXISTS idx_mmcb_focus ON maturity_model_context_bindings(focus_area_id);

-- Pro Ebene höchstens eine Zuordnung je Kontext
CREATE UNIQUE INDEX IF NOT EXISTS uq_mmcb_focus_only
    ON maturity_model_context_bindings (focus_area_id)
    WHERE style_direction_id IS NULL AND training_type_id IS NULL;

CREATE UNIQUE INDEX IF NOT EXISTS uq_mmcb_focus_style
    ON maturity_model_context_bindings (focus_area_id, style_direction_id)
    WHERE style_direction_id IS NOT NULL AND training_type_id IS NULL;

CREATE UNIQUE INDEX IF NOT EXISTS uq_mmcb_focus_style_ttype
    ON maturity_model_context_bindings (focus_area_id, style_direction_id, training_type_id)
    WHERE training_type_id IS NOT NULL;
