-- MSIN-4482 — Templates mapping import participants (hors transaction)
-- Contexte : UI import fiche événement superadm ; upsert sur clé fichier
-- Notes : exécution UNIQUEMENT sur dev préprod ; autres env = Navicat structure + sync_static_db

SET @db := DATABASE();

-- Templates de mapping colonnes (réutilisables par empreinte d'en-têtes)
CREATE TABLE IF NOT EXISTS `inscriptions_import_templates` (
  `tpl_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `eve_id` int(10) unsigned NOT NULL DEFAULT 0,
  `com_id` int(10) unsigned NOT NULL DEFAULT 0 COMMENT 'MSIN-4482 — 0 = lié événement ; >0 = réutilisable côté client',
  `tpl_name` varchar(120) NOT NULL DEFAULT '',
  `tpl_header_sig` char(40) NOT NULL DEFAULT '' COMMENT 'sha1 en-têtes normalisés',
  `tpl_headers_json` mediumtext NOT NULL,
  `tpl_mapping_json` mediumtext NOT NULL COMMENT 'colonnes + valeurs épreuve + questions',
  `tpl_actif` tinyint(1) unsigned NOT NULL DEFAULT 1,
  `tpl_usa_id` int(10) unsigned NOT NULL DEFAULT 0,
  `tpl_creation` datetime NOT NULL,
  `tpl_maj` datetime NOT NULL,
  PRIMARY KEY (`tpl_id`),
  KEY `idx_import_tpl_eve_sig` (`eve_id`, `tpl_header_sig`),
  KEY `idx_import_tpl_com_sig` (`com_id`, `tpl_header_sig`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Clé unique fichier (= external_id ChronoTrack) + origine d'entrée
SET @col_ext := (
    SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'resultats_participants' AND COLUMN_NAME = 'par_external_id'
);
SET @sql_ext := IF(
    @col_ext = 0,
    'ALTER TABLE resultats_participants ADD COLUMN par_external_id VARCHAR(64) NULL DEFAULT NULL COMMENT ''MSIN-4482 — clé unique import / CT external_id'' AFTER par_id_original',
    'SELECT ''par_external_id already exists'' AS note'
);
PREPARE stmt_ext FROM @sql_ext;
EXECUTE stmt_ext;
DEALLOCATE PREPARE stmt_ext;

SET @col_ori := (
    SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'resultats_participants' AND COLUMN_NAME = 'par_origine'
);
SET @sql_ori := IF(
    @col_ori = 0,
    'ALTER TABLE resultats_participants ADD COLUMN par_origine VARCHAR(32) NULL DEFAULT NULL COMMENT ''MSIN-4482 — import_fichier|saisie_rapide|inscription_en_ligne'' AFTER par_external_id',
    'SELECT ''par_origine already exists'' AS note'
);
PREPARE stmt_ori FROM @sql_ori;
EXECUTE stmt_ori;
DEALLOCATE PREPARE stmt_ori;

SET @idx_ext := (
    SELECT COUNT(*) FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'resultats_participants' AND INDEX_NAME = 'idx_par_external_eve'
);
SET @sql_idx := IF(
    @idx_ext = 0,
    'ALTER TABLE resultats_participants ADD KEY idx_par_external_eve (eve_id, par_external_id)',
    'SELECT ''idx_par_external_eve already exists'' AS note'
);
PREPARE stmt_idx FROM @sql_idx;
EXECUTE stmt_idx;
DEALLOCATE PREPARE stmt_idx;
