-- Migration 036: Rahmenprogramm — nur Bibliothek + Kontext-Stammdaten (Fokus, Stil, Typen, Zielgruppen)
-- Grund: Zuordnung zu Gruppen/Kalender nur aus der Planung (Kopie + Lineage), nicht am Rahmenkopf.

-- ── Kontext am Rahmenkopf (Zuordenbarkeit / Filter) ─────────────────────────
ALTER TABLE training_framework_programs
    ADD COLUMN IF NOT EXISTS focus_area_id INT REFERENCES focus_areas(id) ON DELETE SET NULL,
    ADD COLUMN IF NOT EXISTS style_direction_id INT REFERENCES style_directions(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_training_framework_programs_focus ON training_framework_programs(focus_area_id);
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_style ON training_framework_programs(style_direction_id);

-- ── M:N Trainingsstile (training_types Katalog) ─────────────────────────────
CREATE TABLE IF NOT EXISTS training_framework_program_training_types (
    framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
    training_type_id INT NOT NULL REFERENCES training_types(id) ON DELETE CASCADE,
    PRIMARY KEY (framework_program_id, training_type_id)
);

CREATE INDEX IF NOT EXISTS idx_tfptt_type ON training_framework_program_training_types(training_type_id);

-- ── M:N Zielgruppen ─────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS training_framework_program_target_groups (
    framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
    target_group_id INT NOT NULL REFERENCES target_groups(id) ON DELETE CASCADE,
    PRIMARY KEY (framework_program_id, target_group_id)
);

CREATE INDEX IF NOT EXISTS idx_tfptg_tg ON training_framework_program_target_groups(target_group_id);

-- ── Kein „Konkret“ mehr: Slots nicht an Kalender-Einheiten hängen ───────────
UPDATE training_framework_slots SET training_unit_id = NULL WHERE training_unit_id IS NOT NULL;

-- Gruppe/Modus vom Rahmen lösen (Historie: evtl. noch concrete + group_id gesetzt)
UPDATE training_framework_programs SET group_id = NULL;

DROP INDEX IF EXISTS idx_training_framework_programs_group;

ALTER TABLE training_framework_programs DROP CONSTRAINT IF EXISTS training_framework_programs_group_id_fkey;

ALTER TABLE training_framework_programs DROP COLUMN IF EXISTS group_id;

-- Inline-CHECK(s) aus Migration 035 (plan_mode + group-Kombination) entfernen
DO $$
DECLARE
  r RECORD;
BEGIN
  FOR r IN (
    SELECT c.conname AS cn
    FROM pg_constraint c
    WHERE c.conrelid = 'public.training_framework_programs'::regclass
      AND c.contype = 'c'
      AND (
        pg_get_constraintdef(c.oid) ILIKE '%plan_mode%'
        OR pg_get_constraintdef(c.oid) ILIKE '%group_id%'
      )
  )
  LOOP
    EXECUTE format('ALTER TABLE training_framework_programs DROP CONSTRAINT %I', r.cn);
  END LOOP;
END $$;

ALTER TABLE training_framework_programs DROP COLUMN IF EXISTS plan_mode;

DROP INDEX IF EXISTS idx_training_framework_programs_mode;
