-- =====================================================================
-- unites_par_annee.sql  --  PHASE 1 : unites de formation et elements PAR ANNEE
--
-- Objet : porter l'annee sur n_unites_formation (uf_annee_id) et eclater les
-- unites / elements (n_elements_modules) existants par annee d'activite, de
-- sorte qu'une annee passee ne soit plus jamais modifiee par l'annee suivante.
--
-- AVANT DE LANCER : SAUVEGARDE COMPLETE de la base (mysqldump --single-transaction
--   --routines --triggers). Aucun utilisateur ne doit travailler pendant l'execution.
-- Compatible MySQL 8 et MariaDB >= 10.3 ; pas de procedure stockee ; tables de
-- travail ordinaires zz_* (supprimees a la fin) -> importable dans phpMyAdmin.
-- Lancer : mysql -h HOTE -P PORT -u USER -p BASE < unites_par_annee.sql
--   ou phpMyAdmin > Importer (decocher "Activer la verification des cles
--   etrangeres" n'est PAS necessaire).
-- Rejouable sans dommage : la section B ne traite que les unites dont
-- uf_annee_id est NULL (donc rien a faire une fois la phase 1 terminee).
--
-- REGLES (voir aussi le rapport) :
--  * Annees d'une unite = annees d'activite de ses elements : n_examens.exam_as_id
--    (+ n_examen_elements), annee d'inscription des n_resultat_emo / n_resultat_uf,
--    annee de n_seances.se_date, annee de n_edt_unites.uet_date_deb, colonnes annee
--    de n_devoirs / n_ressources / n_ressource_chapitres / n_prof_convenu,
--    n_disc_incidents (annee de l'examen sinon de inc_date), n_evaluation_*.
--    + annee COURANTE si la classe est ouverte (debut <= courante <= fin).
--    Sans aucune annee : classe_as_debut_id (a defaut annee courante).
--  * Les id d'origine (uf_id / emo_id) restent a l'annee la PLUS RECENTE ; chaque
--    annee plus ancienne recoit une copie (nouveaux id).
--  * Lignes enfants avec annee naturelle -> repointees vers la copie de leur annee.
--    Lignes sans annee naturelle -> COPIEES vers chaque copie d'element.
-- =====================================================================

SET @schema := DATABASE();
SET @audit_source := 'migration';
SET @audit_context := 'unites_par_annee';

-- =====================================================================
-- (A) STRUCTURE
-- =====================================================================

-- A1) colonne uf_annee_id (NULL pour l'instant)
SET @s := IF((SELECT COUNT(*) FROM information_schema.columns
               WHERE table_schema=@schema AND table_name='n_unites_formation' AND column_name='uf_annee_id')=0,
  'ALTER TABLE n_unites_formation ADD COLUMN uf_annee_id BIGINT UNSIGNED NULL AFTER uf_classe_id', 'DO 0');
PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;

-- A2) index
SET @s := IF((SELECT COUNT(*) FROM information_schema.statistics
               WHERE table_schema=@schema AND table_name='n_unites_formation' AND index_name='idx_uf_annee')=0,
  'ALTER TABLE n_unites_formation ADD INDEX idx_uf_annee (uf_annee_id)', 'DO 0');
PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;

-- A3) cle etrangere vers n_annees_scolaires
SET @s := IF((SELECT COUNT(*) FROM information_schema.table_constraints
               WHERE table_schema=@schema AND table_name='n_unites_formation'
                 AND constraint_name='n_unites_formation_uf_annee_id_foreign' AND constraint_type='FOREIGN KEY')=0,
  'ALTER TABLE n_unites_formation ADD CONSTRAINT n_unites_formation_uf_annee_id_foreign FOREIGN KEY (uf_annee_id) REFERENCES n_annees_scolaires (as_id)', 'DO 0');
PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;

-- A4) l'ancienne cle unique (classe, sem, module, matiere) empecherait les copies par annee :
--     on la remplace par un index simple (la nouvelle unique (emo_uf_id, emo_mat_id) vient en phase 2).
SET @s := IF((SELECT COUNT(*) FROM information_schema.statistics
               WHERE table_schema=@schema AND table_name='n_elements_modules' AND index_name='idx_emo_classe_sem')=0,
  'ALTER TABLE n_elements_modules ADD INDEX idx_emo_classe_sem (emo_classe_id, emo_sem_id)', 'DO 0');
PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;

SET @s := IF((SELECT COUNT(*) FROM information_schema.statistics
               WHERE table_schema=@schema AND table_name='n_elements_modules' AND index_name='uq_emo_classe_sem_mod_mat')>0,
  'ALTER TABLE n_elements_modules DROP INDEX uq_emo_classe_sem_mod_mat', 'DO 0');
PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;

-- =====================================================================
-- (B) DONNEES
-- =====================================================================
DROP TABLE IF EXISTS zz_nouf;
DROP TABLE IF EXISTS zz_emo_an;
DROP TABLE IF EXISTS zz_uf_an;
DROP TABLE IF EXISTS zz_cur;
DROP TABLE IF EXISTS zz_map_uf;
DROP TABLE IF EXISTS zz_map_emo;
DROP TABLE IF EXISTS zz_map_seq;

-- B1) elements SANS unite (emo_uf_id NULL) : on cree une unite 1:1 pour chacun
CREATE TABLE zz_nouf (
  n INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  emo_id BIGINT UNSIGNED NOT NULL,
  new_uf_id BIGINT UNSIGNED NULL
) ENGINE=InnoDB;
INSERT INTO zz_nouf (emo_id)
  SELECT emo_id FROM n_elements_modules WHERE emo_uf_id IS NULL ORDER BY emo_id;
SET @base_uf := (SELECT COALESCE(MAX(uf_id),0) FROM n_unites_formation);
UPDATE zz_nouf SET new_uf_id = @base_uf + n;
INSERT INTO n_unites_formation
  (uf_id, uf_classe_id, uf_annee_id, uf_sem_id, uf_mat_id, uf_code, uf_index, uf_domaine_id,
   uf_coef, uf_type, uf_visible_pv, created_at, updated_at, created_by)
SELECT z.new_uf_id, e.emo_classe_id, NULL, e.emo_sem_id, e.emo_mat_id, e.emo_code, e.emo_mod_index, NULL,
       e.emo_coef, e.emo_type, e.emo_est_visible_pv, e.created_at, e.updated_at, e.created_by
  FROM zz_nouf z JOIN n_elements_modules e ON e.emo_id = z.emo_id;
UPDATE n_elements_modules e JOIN zz_nouf z ON z.emo_id = e.emo_id
   SET e.emo_uf_id = z.new_uf_id, e.updated_at = e.updated_at;

-- B2) annees d'activite par element
CREATE TABLE zz_emo_an (
  emo_id BIGINT UNSIGNED NOT NULL,
  as_id  BIGINT UNSIGNED NOT NULL,
  PRIMARY KEY (emo_id, as_id)
) ENGINE=InnoDB;

INSERT IGNORE INTO zz_emo_an SELECT exam_emo_id, exam_as_id FROM n_examens;
INSERT IGNORE INTO zz_emo_an SELECT x.ee_emo_id, e.exam_as_id FROM n_examen_elements x JOIN n_examens e ON e.exam_id = x.ee_exam_id;
INSERT IGNORE INTO zz_emo_an SELECT r.rn_emo_id, i.ins_as_id FROM n_resultat_emo r JOIN n_inscriptions i ON i.ins_id = r.rn_ins_id WHERE i.ins_as_id IS NOT NULL;
INSERT IGNORE INTO zz_emo_an SELECT s.se_emo_id, a.as_id FROM n_seances s JOIN n_annees_scolaires a ON s.se_date BETWEEN a.as_date_debut AND a.as_date_fin;
INSERT IGNORE INTO zz_emo_an SELECT u.uet_emo_id, a.as_id FROM n_edt_unites u JOIN n_annees_scolaires a ON u.uet_date_deb BETWEEN a.as_date_debut AND a.as_date_fin;
INSERT IGNORE INTO zz_emo_an SELECT dev_emo_id, dev_as_id FROM n_devoirs;
INSERT IGNORE INTO zz_emo_an SELECT res_emo_id, res_as_id FROM n_ressources;
INSERT IGNORE INTO zz_emo_an SELECT rch_emo_id, rch_as_id FROM n_ressource_chapitres;
INSERT IGNORE INTO zz_emo_an SELECT pfc_emo_id, pfc_as_id FROM n_prof_convenu;
INSERT IGNORE INTO zz_emo_an SELECT d.inc_emo_id, e.exam_as_id FROM n_disc_incidents d JOIN n_examens e ON e.exam_id = d.inc_exam_id WHERE d.inc_emo_id IS NOT NULL;
INSERT IGNORE INTO zz_emo_an SELECT d.inc_emo_id, a.as_id FROM n_disc_incidents d JOIN n_annees_scolaires a ON d.inc_date BETWEEN a.as_date_debut AND a.as_date_fin WHERE d.inc_emo_id IS NOT NULL AND d.inc_exam_id IS NULL;
INSERT IGNORE INTO zz_emo_an SELECT p.evp_emo_id, i.ins_as_id FROM n_evaluation_participations p JOIN n_inscriptions i ON i.ins_id = p.evp_ins_id WHERE i.ins_as_id IS NOT NULL;
INSERT IGNORE INTO zz_emo_an SELECT r.evr_emo_id, c.evc_as_id FROM n_evaluation_reponses r JOIN n_evaluation_campagnes c ON c.evc_id = r.evr_evc_id WHERE c.evc_as_id IS NOT NULL;

-- B3) annees par unite (seulement les unites encore sans annee)
CREATE TABLE zz_uf_an (
  uf_id BIGINT UNSIGNED NOT NULL,
  as_id BIGINT UNSIGNED NOT NULL,
  d DATE NOT NULL,
  PRIMARY KEY (uf_id, as_id)
) ENGINE=InnoDB;

INSERT IGNORE INTO zz_uf_an (uf_id, as_id, d)
SELECT e.emo_uf_id, a.as_id, y.as_date_debut
  FROM zz_emo_an a
  JOIN n_elements_modules e ON e.emo_id = a.emo_id
  JOIN n_unites_formation u ON u.uf_id = e.emo_uf_id AND u.uf_annee_id IS NULL
  JOIN n_annees_scolaires y ON y.as_id = a.as_id;

INSERT IGNORE INTO zz_uf_an (uf_id, as_id, d)
SELECT r.ru_uf_id, i.ins_as_id, y.as_date_debut
  FROM n_resultat_uf r
  JOIN n_inscriptions i ON i.ins_id = r.ru_ins_id
  JOIN n_unites_formation u ON u.uf_id = r.ru_uf_id AND u.uf_annee_id IS NULL
  JOIN n_annees_scolaires y ON y.as_id = i.ins_as_id;

-- annee courante (une seule, la plus recente si plusieurs sont marquees)
CREATE TABLE zz_cur (as_id BIGINT UNSIGNED NOT NULL PRIMARY KEY, d DATE NOT NULL, f DATE NOT NULL) ENGINE=InnoDB;
INSERT INTO zz_cur (as_id, d, f)
  SELECT as_id, as_date_debut, as_date_fin FROM n_annees_scolaires
   WHERE as_est_courante = 1 ORDER BY as_date_debut DESC LIMIT 1;

-- + annee courante pour les unites dont la classe est ouverte maintenant
INSERT IGNORE INTO zz_uf_an (uf_id, as_id, d)
SELECT u.uf_id, cur.as_id, cur.d
  FROM n_unites_formation u
  JOIN n_classes c ON c.classe_id = u.uf_classe_id
  JOIN n_annees_scolaires da ON da.as_id = c.classe_as_debut_id
  JOIN n_annees_scolaires fa ON fa.as_id = c.classe_as_fin_id
  JOIN zz_cur cur ON da.as_date_debut <= cur.d AND fa.as_date_fin >= cur.f
 WHERE u.uf_annee_id IS NULL;

-- unites sans aucune annee : annee de debut de la classe, a defaut annee courante, a defaut la plus ancienne
INSERT IGNORE INTO zz_uf_an (uf_id, as_id, d)
SELECT u.uf_id, y.as_id, y.as_date_debut
  FROM n_unites_formation u
  JOIN n_classes c ON c.classe_id = u.uf_classe_id
  JOIN n_annees_scolaires y ON y.as_id = COALESCE(c.classe_as_debut_id,
                                                  (SELECT as_id FROM zz_cur),
                                                  (SELECT MIN(as_id) FROM n_annees_scolaires))
 WHERE u.uf_annee_id IS NULL
   AND NOT EXISTS (SELECT 1 FROM zz_uf_an z WHERE z.uf_id = u.uf_id);

-- B4) table de correspondance des unites ; l'original garde l'annee la plus recente
CREATE TABLE zz_map_uf (
  n INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  uf_id BIGINT UNSIGNED NOT NULL,
  as_id BIGINT UNSIGNED NOT NULL,
  d DATE NOT NULL,
  new_uf_id BIGINT UNSIGNED NULL,
  UNIQUE KEY uq_zz_map_uf (uf_id, as_id)
) ENGINE=InnoDB;
INSERT INTO zz_map_uf (uf_id, as_id, d) SELECT uf_id, as_id, d FROM zz_uf_an ORDER BY uf_id, d;

UPDATE zz_map_uf m
  JOIN (SELECT uf_id, MAX(d) AS dmax FROM zz_uf_an GROUP BY uf_id) x ON x.uf_id = m.uf_id AND x.dmax = m.d
   SET m.new_uf_id = m.uf_id;
SET @base_uf := (SELECT COALESCE(MAX(uf_id),0) FROM n_unites_formation);
UPDATE zz_map_uf SET new_uf_id = @base_uf + n WHERE new_uf_id IS NULL;

-- B5) table de correspondance des elements (tous les elements x toutes les annees de leur unite)
CREATE TABLE zz_map_emo (
  n INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  emo_id BIGINT UNSIGNED NOT NULL,
  as_id  BIGINT UNSIGNED NOT NULL,
  new_emo_id BIGINT UNSIGNED NULL,
  new_uf_id  BIGINT UNSIGNED NOT NULL,
  UNIQUE KEY uq_zz_map_emo (emo_id, as_id),
  KEY idx_zz_map_emo_new (new_emo_id)
) ENGINE=InnoDB;
INSERT INTO zz_map_emo (emo_id, as_id, new_uf_id)
SELECT e.emo_id, m.as_id, m.new_uf_id
  FROM n_elements_modules e JOIN zz_map_uf m ON m.uf_id = e.emo_uf_id
 ORDER BY e.emo_id, m.d;
UPDATE zz_map_emo me JOIN zz_map_uf mu ON mu.new_uf_id = me.new_uf_id AND mu.uf_id = mu.new_uf_id
   SET me.new_emo_id = me.emo_id;
SET @base_emo := (SELECT COALESCE(MAX(emo_id),0) FROM n_elements_modules);
UPDATE zz_map_emo SET new_emo_id = @base_emo + n WHERE new_emo_id IS NULL;

-- B6) creation des unites copies (annees plus anciennes) + annee des originaux
INSERT INTO n_unites_formation
  (uf_id, uf_classe_id, uf_annee_id, uf_sem_id, uf_mat_id, uf_code, uf_index, uf_domaine_id, uf_coef, uf_type,
   uf_objectif_general, uf_responsable_prof_id, uf_visible_pv, created_at, updated_at, created_by)
SELECT m.new_uf_id, u.uf_classe_id, m.as_id, u.uf_sem_id, u.uf_mat_id, u.uf_code, u.uf_index, u.uf_domaine_id, u.uf_coef, u.uf_type,
       u.uf_objectif_general, u.uf_responsable_prof_id, u.uf_visible_pv, u.created_at, u.updated_at, u.created_by
  FROM zz_map_uf m JOIN n_unites_formation u ON u.uf_id = m.uf_id
 WHERE m.new_uf_id <> m.uf_id;

UPDATE n_unites_formation u JOIN zz_map_uf m ON m.uf_id = u.uf_id AND m.new_uf_id = m.uf_id
   SET u.uf_annee_id = m.as_id, u.updated_at = u.updated_at;

INSERT INTO n_competences (comp_uf_id, comp_libelle, comp_ordre, created_at, updated_at, created_by)
SELECT m.new_uf_id, c.comp_libelle, c.comp_ordre, c.created_at, c.updated_at, c.created_by
  FROM zz_map_uf m JOIN n_competences c ON c.comp_uf_id = m.uf_id
 WHERE m.new_uf_id <> m.uf_id;

-- B7) creation des elements copies
-- (emo_mod_id n'existe plus apres la phase 2 : la liste de colonnes est donc construite dynamiquement)
SET @has_mod := (SELECT COUNT(*) FROM information_schema.columns
                  WHERE table_schema=@schema AND table_name='n_elements_modules' AND column_name='emo_mod_id');
SET @s := CONCAT(
  'INSERT INTO n_elements_modules (emo_id, emo_classe_id, ', IF(@has_mod>0,'emo_mod_id, ',''),
  'emo_mod_index, emo_mat_id, emo_sem_id, emo_prof_cours_id, emo_prof_td_id, emo_prof_p_id, emo_prof_h_id, ',
  'emo_coef, emo_nb_heures, emo_heures_cm, emo_heures_td, emo_heures_tp, emo_type, emo_est_visible_pv, emo_est_enseigne, ',
  'created_at, updated_at, created_by, updated_by, emo_uf_id, emo_code) ',
  'SELECT m.new_emo_id, e.emo_classe_id, ', IF(@has_mod>0,'e.emo_mod_id, ',''),
  'e.emo_mod_index, e.emo_mat_id, e.emo_sem_id, e.emo_prof_cours_id, e.emo_prof_td_id, e.emo_prof_p_id, e.emo_prof_h_id, ',
  'e.emo_coef, e.emo_nb_heures, e.emo_heures_cm, e.emo_heures_td, e.emo_heures_tp, e.emo_type, e.emo_est_visible_pv, e.emo_est_enseigne, ',
  'e.created_at, e.updated_at, e.created_by, e.updated_by, m.new_uf_id, e.emo_code ',
  'FROM zz_map_emo m JOIN n_elements_modules e ON e.emo_id = m.emo_id WHERE m.new_emo_id <> m.emo_id');
PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;

-- B8) REPOINTAGE des lignes enfants qui ont une annee naturelle (on garde updated_at inchange)
UPDATE n_examens t JOIN zz_map_emo m ON m.emo_id = t.exam_emo_id AND m.as_id = t.exam_as_id
   SET t.exam_emo_id = m.new_emo_id, t.updated_at = t.updated_at WHERE m.new_emo_id <> m.emo_id;

UPDATE n_examen_elements t
  JOIN n_examens e ON e.exam_id = t.ee_exam_id
  JOIN zz_map_emo m ON m.emo_id = t.ee_emo_id AND m.as_id = e.exam_as_id
   SET t.ee_emo_id = m.new_emo_id, t.updated_at = t.updated_at WHERE m.new_emo_id <> m.emo_id;

UPDATE n_resultat_emo t
  JOIN n_inscriptions i ON i.ins_id = t.rn_ins_id
  JOIN zz_map_emo m ON m.emo_id = t.rn_emo_id AND m.as_id = i.ins_as_id
   SET t.rn_emo_id = m.new_emo_id, t.updated_at = t.updated_at WHERE m.new_emo_id <> m.emo_id;

UPDATE n_resultat_uf t
  JOIN n_inscriptions i ON i.ins_id = t.ru_ins_id
  JOIN zz_map_uf m ON m.uf_id = t.ru_uf_id AND m.as_id = i.ins_as_id
   SET t.ru_uf_id = m.new_uf_id, t.updated_at = t.updated_at WHERE m.new_uf_id <> m.uf_id;

UPDATE n_seances t
  JOIN n_annees_scolaires a ON t.se_date BETWEEN a.as_date_debut AND a.as_date_fin
  JOIN zz_map_emo m ON m.emo_id = t.se_emo_id AND m.as_id = a.as_id
   SET t.se_emo_id = m.new_emo_id, t.updated_at = t.updated_at WHERE m.new_emo_id <> m.emo_id;

UPDATE n_edt_unites t
  JOIN n_annees_scolaires a ON t.uet_date_deb BETWEEN a.as_date_debut AND a.as_date_fin
  JOIN zz_map_emo m ON m.emo_id = t.uet_emo_id AND m.as_id = a.as_id
   SET t.uet_emo_id = m.new_emo_id, t.updated_at = t.updated_at WHERE m.new_emo_id <> m.emo_id;

UPDATE n_devoirs t JOIN zz_map_emo m ON m.emo_id = t.dev_emo_id AND m.as_id = t.dev_as_id
   SET t.dev_emo_id = m.new_emo_id, t.updated_at = t.updated_at WHERE m.new_emo_id <> m.emo_id;

UPDATE n_ressources t JOIN zz_map_emo m ON m.emo_id = t.res_emo_id AND m.as_id = t.res_as_id
   SET t.res_emo_id = m.new_emo_id, t.updated_at = t.updated_at WHERE m.new_emo_id <> m.emo_id;

UPDATE n_ressource_chapitres t JOIN zz_map_emo m ON m.emo_id = t.rch_emo_id AND m.as_id = t.rch_as_id
   SET t.rch_emo_id = m.new_emo_id, t.updated_at = t.updated_at WHERE m.new_emo_id <> m.emo_id;

UPDATE n_prof_convenu t JOIN zz_map_emo m ON m.emo_id = t.pfc_emo_id AND m.as_id = t.pfc_as_id
   SET t.pfc_emo_id = m.new_emo_id, t.updated_at = t.updated_at WHERE m.new_emo_id <> m.emo_id;

UPDATE n_disc_incidents t
  JOIN n_examens e ON e.exam_id = t.inc_exam_id
  JOIN zz_map_emo m ON m.emo_id = t.inc_emo_id AND m.as_id = e.exam_as_id
   SET t.inc_emo_id = m.new_emo_id, t.updated_at = t.updated_at WHERE m.new_emo_id <> m.emo_id;
UPDATE n_disc_incidents t
  JOIN n_annees_scolaires a ON t.inc_date BETWEEN a.as_date_debut AND a.as_date_fin
  JOIN zz_map_emo m ON m.emo_id = t.inc_emo_id AND m.as_id = a.as_id
   SET t.inc_emo_id = m.new_emo_id, t.updated_at = t.updated_at WHERE t.inc_exam_id IS NULL AND m.new_emo_id <> m.emo_id;

UPDATE n_evaluation_participations t
  JOIN n_inscriptions i ON i.ins_id = t.evp_ins_id
  JOIN zz_map_emo m ON m.emo_id = t.evp_emo_id AND m.as_id = i.ins_as_id
   SET t.evp_emo_id = m.new_emo_id WHERE m.new_emo_id <> m.emo_id;

UPDATE n_evaluation_reponses t
  JOIN n_evaluation_campagnes c ON c.evc_id = t.evr_evc_id
  JOIN zz_map_emo m ON m.emo_id = t.evr_emo_id AND m.as_id = c.evc_as_id
   SET t.evr_emo_id = m.new_emo_id WHERE m.new_emo_id <> m.emo_id;

-- B9) COPIE des lignes enfants SANS annee naturelle vers chaque copie d'element
INSERT INTO n_element_affectations (aff_emo_id, aff_groupe_id, aff_periode, aff_role, aff_prof_id, aff_nbh, created_at, updated_at, created_by)
SELECT m.new_emo_id, a.aff_groupe_id, a.aff_periode, a.aff_role, a.aff_prof_id, a.aff_nbh, a.created_at, a.updated_at, a.created_by
  FROM zz_map_emo m JOIN n_element_affectations a ON a.aff_emo_id = m.emo_id WHERE m.new_emo_id <> m.emo_id;

INSERT INTO n_prof_elements (pe_emo_id, pe_prof_id, pe_mode_id, pe_grp_id, created_at, updated_at, created_by)
SELECT m.new_emo_id, p.pe_prof_id, p.pe_mode_id, p.pe_grp_id, p.created_at, p.updated_at, p.created_by
  FROM zz_map_emo m JOIN n_prof_elements p ON p.pe_emo_id = m.emo_id WHERE m.new_emo_id <> m.emo_id;

INSERT INTO n_encadrants_projets (ep_emo_id, ep_gp_id, ep_prof_id, created_at, updated_at, created_by)
SELECT m.new_emo_id, p.ep_gp_id, p.ep_prof_id, p.created_at, p.updated_at, p.created_by
  FROM zz_map_emo m JOIN n_encadrants_projets p ON p.ep_emo_id = m.emo_id WHERE m.new_emo_id <> m.emo_id;

-- sequences pedagogiques : id explicites pour pouvoir remapper objectifs et commentaires
CREATE TABLE zz_map_seq (
  n INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  seq_id BIGINT UNSIGNED NOT NULL,
  new_emo_id BIGINT UNSIGNED NOT NULL,
  new_seq_id BIGINT UNSIGNED NULL,
  UNIQUE KEY uq_zz_map_seq (seq_id, new_emo_id)
) ENGINE=InnoDB;
INSERT INTO zz_map_seq (seq_id, new_emo_id)
SELECT s.seq_id, m.new_emo_id FROM zz_map_emo m JOIN n_sequences_pedagogiques s ON s.seq_emo_id = m.emo_id
 WHERE m.new_emo_id <> m.emo_id ORDER BY s.seq_id, m.new_emo_id;
SET @base_seq := (SELECT COALESCE(MAX(seq_id),0) FROM n_sequences_pedagogiques);
UPDATE zz_map_seq SET new_seq_id = @base_seq + n;
INSERT INTO n_sequences_pedagogiques (seq_id, seq_emo_id, seq_ordre, seq_titre, seq_objectif_inter, seq_duree, created_at, updated_at, created_by)
SELECT z.new_seq_id, z.new_emo_id, s.seq_ordre, s.seq_titre, s.seq_objectif_inter, s.seq_duree, s.created_at, s.updated_at, s.created_by
  FROM zz_map_seq z JOIN n_sequences_pedagogiques s ON s.seq_id = z.seq_id;

INSERT INTO n_objectifs_programme (obj_emo_id, obj_seq_id, obj_ordre, obj_titre, obj_description, obj_type, obj_duree, obj_actif, created_at, updated_at, created_by)
SELECT m.new_emo_id, zs.new_seq_id, o.obj_ordre, o.obj_titre, o.obj_description, o.obj_type, o.obj_duree, o.obj_actif, o.created_at, o.updated_at, o.created_by
  FROM zz_map_emo m
  JOIN n_objectifs_programme o ON o.obj_emo_id = m.emo_id
  LEFT JOIN zz_map_seq zs ON zs.seq_id = o.obj_seq_id AND zs.new_emo_id = m.new_emo_id
 WHERE m.new_emo_id <> m.emo_id;

INSERT INTO n_avancement_commentaires (avc_emo_id, avc_groupe_id, avc_periode, avc_seq_id, avc_commentaire, avc_modifie_par, created_at, updated_at, created_by)
SELECT m.new_emo_id, c.avc_groupe_id, c.avc_periode, zs.new_seq_id, c.avc_commentaire, c.avc_modifie_par, c.created_at, c.updated_at, c.created_by
  FROM zz_map_emo m
  JOIN n_avancement_commentaires c ON c.avc_emo_id = m.emo_id
  LEFT JOIN zz_map_seq zs ON zs.seq_id = c.avc_seq_id AND zs.new_emo_id = m.new_emo_id
 WHERE m.new_emo_id <> m.emo_id;

-- B10) nettoyage des tables de travail
DROP TABLE IF EXISTS zz_map_seq;
DROP TABLE IF EXISTS zz_map_emo;
DROP TABLE IF EXISTS zz_map_uf;
DROP TABLE IF EXISTS zz_cur;
DROP TABLE IF EXISTS zz_uf_an;
DROP TABLE IF EXISTS zz_emo_an;
DROP TABLE IF EXISTS zz_nouf;

-- =====================================================================
-- (C) CONTRAINTES : echouent volontairement s'il reste des NULL
-- =====================================================================
ALTER TABLE n_unites_formation MODIFY uf_annee_id BIGINT UNSIGNED NOT NULL;
ALTER TABLE n_elements_modules MODIFY emo_uf_id BIGINT UNSIGNED NOT NULL;
-- Fin phase 1.
