-- Migration: Ajout du champ convention_id à la table projets
-- Date: 2025-01-XX
-- Description: Ajoute le champ convention_id à la table projets pour permettre de lier un projet à une convention (plusieurs projets peuvent avoir la même convention, donc pas de contrainte unique).

SET @dbname = DATABASE();
SET @tablename = 'projets';
SET @column = 'convention_id';

-- Vérifier et ajouter convention_id
SET @preparedStatement = (SELECT IF(
  (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
      (TABLE_SCHEMA = @dbname)
      AND (TABLE_NAME = @tablename)
      AND (COLUMN_NAME = @column)
  ) > 0,
  'SELECT "La colonne convention_id existe déjà." AS message;',
  CONCAT('ALTER TABLE `', @tablename, '` ADD COLUMN `', @column, '` int NULL DEFAULT NULL COMMENT "ID de la convention" AFTER `decision_id`;')
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

-- Ajouter l'index pour convention_id (sans contrainte unique)
SET @indexName = 'idx_convention_id';
SET @preparedStatement2 = (SELECT IF(
  (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
    WHERE
      (TABLE_SCHEMA = @dbname)
      AND (TABLE_NAME = @tablename)
      AND (INDEX_NAME = @indexName)
  ) > 0,
  'SELECT "L\'index idx_convention_id existe déjà." AS message;',
  CONCAT('CREATE INDEX `', @indexName, '` ON `', @tablename, '` (`', @column, '` ASC) USING BTREE;')
));
PREPARE createIndexIfNotExists FROM @preparedStatement2;
EXECUTE createIndexIfNotExists;
DEALLOCATE PREPARE createIndexIfNotExists;

-- Ajouter la clé étrangère vers conventions
SET @fkName = 'projets_ibfk_convention';
SET @preparedStatement3 = (SELECT IF(
  (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
    WHERE
      (TABLE_SCHEMA = @dbname)
      AND (TABLE_NAME = @tablename)
      AND (CONSTRAINT_NAME = @fkName)
  ) > 0,
  'SELECT "La clé étrangère projets_ibfk_convention existe déjà." AS message;',
  CONCAT('ALTER TABLE `', @tablename, '` ADD CONSTRAINT `', @fkName, '` FOREIGN KEY (`', @column, '`) REFERENCES `conventions` (`id`) ON DELETE SET NULL ON UPDATE RESTRICT;')
));
PREPARE createFKIfNotExists FROM @preparedStatement3;
EXECUTE createFKIfNotExists;
DEALLOCATE PREPARE createFKIfNotExists;

-- Message de confirmation
SELECT "Migration 013: Ajout du champ convention_id à la table projets terminée avec succès." AS message;

