-- Formations du centre Miage Ksar El Kébir (diplômes et filières communs avec Temara), ouvertes de 2025-2026 à 2026-2027, accréditées, en français.
-- À exécuter après creer_centre_ksar_el_kebir.sql. Sans risque : une formation déjà présente (même centre, même code) n'est pas recréée.

SET @ksar := (SELECT ct_id FROM n_centres WHERE ct_code = 'KSAR');
SET @debut := (SELECT as_id FROM n_annees_scolaires WHERE as_nom = '2025-2026');
SET @fin := (SELECT as_id FROM n_annees_scolaires WHERE as_nom = '2026-2027');

INSERT INTO n_formations (for_centre_id, for_abbr, for_nom, for_diplome_id, for_filiere_id, for_option_id, for_est_accreditee, for_langue,
    for_code_filiere, for_code_option, for_as_debut_id, for_as_fin_id, created_at)
SELECT @ksar, x.code, x.nom, d.dip_id, fl.fil_id, NULL, 1, 'fr', fl.fil_code_inscription, NULL, @debut, @fin, NOW()
FROM (
  SELECT 'DTS-SRI-25' code, 'Technicien Spécialisé Systèmes et Réseaux Informatiques' nom, 'TS' dip, 'SRI' fil
  UNION ALL SELECT 'DTS-DI-25', 'Technicien Spécialisé Développement Informatique', 'TS', 'DI'
  UNION ALL SELECT 'DTS-GE-25', 'Technicien Spécialisé Gestion des Entreprises', 'TS', 'GE'
  UNION ALL SELECT 'DT-GI-25', 'Technicien Gestion Informatisée', 'T', 'GI'
) x
JOIN n_diplomes d ON d.dip_abbr = x.dip
JOIN n_filieres fl ON fl.fil_abbr = x.fil
WHERE @ksar IS NOT NULL
  AND NOT EXISTS (SELECT 1 FROM n_formations f WHERE f.for_centre_id = @ksar AND f.for_abbr = x.code);

-- Vérification : 4 lignes attendues
SELECT f.for_id, f.for_abbr, f.for_nom, d.dip_abbr AS diplome, fl.fil_abbr AS filiere, d.dip_nb_annees AS duree,
       a1.as_nom AS debut, a2.as_nom AS fin, f.for_est_accreditee AS accreditee, f.for_langue AS langue
FROM n_formations f
JOIN n_diplomes d ON d.dip_id = f.for_diplome_id
JOIN n_filieres fl ON fl.fil_id = f.for_filiere_id
LEFT JOIN n_annees_scolaires a1 ON a1.as_id = f.for_as_debut_id
LEFT JOIN n_annees_scolaires a2 ON a2.as_id = f.for_as_fin_id
WHERE f.for_centre_id = @ksar
ORDER BY f.for_abbr;
