-- Geplante Gesamt- und Abschnittsdauer; Rahmenprogramm: Fokus/Stil als M:N (wie Trainingsarten/Zielgruppen)

ALTER TABLE training_units
    ADD COLUMN IF NOT EXISTS planned_duration_min INT;

ALTER TABLE training_unit_sections
    ADD COLUMN IF NOT EXISTS planned_duration_min INT;

ALTER TABLE training_plan_template_sections
    ADD COLUMN IF NOT EXISTS planned_duration_min INT;

CREATE TABLE IF NOT EXISTS training_framework_program_focus_areas (
    framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
    focus_area_id INT NOT NULL REFERENCES focus_areas(id) ON DELETE CASCADE,
    PRIMARY KEY (framework_program_id, focus_area_id)
);

CREATE INDEX IF NOT EXISTS idx_tfpfa_focus ON training_framework_program_focus_areas(focus_area_id);

CREATE TABLE IF NOT EXISTS training_framework_program_style_directions (
    framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
    style_direction_id INT NOT NULL REFERENCES style_directions(id) ON DELETE CASCADE,
    PRIMARY KEY (framework_program_id, style_direction_id)
);

CREATE INDEX IF NOT EXISTS idx_tfpsd_style ON training_framework_program_style_directions(style_direction_id);

INSERT INTO training_framework_program_focus_areas (framework_program_id, focus_area_id)
SELECT id, focus_area_id FROM training_framework_programs
WHERE focus_area_id IS NOT NULL
ON CONFLICT DO NOTHING;

INSERT INTO training_framework_program_style_directions (framework_program_id, style_direction_id)
SELECT id, style_direction_id FROM training_framework_programs
WHERE style_direction_id IS NOT NULL
ON CONFLICT DO NOTHING;
