-- Migration: Ajout de la table convention_indicateurs_performance
-- Date: 2025-01-XX
-- Description: Crée la table pour stocker les indicateurs de performance associés aux conventions.
--              Chaque convention peut avoir plusieurs indicateurs avec un nom et un objectif.

-- Vérifier si la table existe déjà avant de la créer
SET @dbname = DATABASE();
SET @tablename = 'convention_indicateurs_performance';
SET @preparedStatement = (SELECT IF(
  (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
    WHERE
      (TABLE_SCHEMA = @dbname)
      AND (TABLE_NAME = @tablename)
  ) > 0,
  'SELECT "La table convention_indicateurs_performance existe déjà." AS message;',
  CONCAT('CREATE TABLE `', @tablename, '` (
    `id` int NOT NULL AUTO_INCREMENT,
    `convention_id` int NOT NULL,
    `indicateur_fr` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT "Nom de l\'indicateur en français",
    `indicateur_ar` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT "Nom de l\'indicateur en arabe",
    `objectif` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT "Objectif de l\'indicateur",
    `ordre` int NOT NULL DEFAULT 0 COMMENT "Ordre d\'affichage",
    `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
    `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`) USING BTREE,
    INDEX `idx_convention`(`convention_id` ASC) USING BTREE,
    INDEX `idx_ordre`(`convention_id` ASC, `ordre` ASC) USING BTREE,
    CONSTRAINT `convention_indicateurs_performance_ibfk_1` FOREIGN KEY (`convention_id`) REFERENCES `conventions` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT
  ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;')
));
PREPARE createIfNotExists FROM @preparedStatement;
EXECUTE createIfNotExists;
DEALLOCATE PREPARE createIfNotExists;

-- Message de confirmation
SELECT "Migration 002: Création de la table convention_indicateurs_performance terminée avec succès." AS message;

