-- Migration: Ajout des champs 2FA à la table users
-- Date: 2025-01-XX
-- Description: Ajoute les champs two_factor_secret et two_factor_enabled pour l'authentification à deux facteurs avec Google Authenticator.

SET @dbname = DATABASE();
SET @tablename = 'users';
SET @column1 = 'two_factor_secret';
SET @column2 = 'two_factor_enabled';

-- Vérifier et ajouter two_factor_secret
SET @preparedStatement1 = (SELECT IF(
  (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
      (TABLE_SCHEMA = @dbname)
      AND (TABLE_NAME = @tablename)
      AND (COLUMN_NAME = @column1)
  ) > 0,
  'SELECT "La colonne two_factor_secret existe déjà." AS message;',
  CONCAT('ALTER TABLE `', @tablename, '` ADD COLUMN `', @column1, '` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT "Secret pour Google Authenticator" AFTER `is_active`;')
));
PREPARE alterIfNotExists1 FROM @preparedStatement1;
EXECUTE alterIfNotExists1;
DEALLOCATE PREPARE alterIfNotExists1;

-- Vérifier et ajouter two_factor_enabled
SET @preparedStatement2 = (SELECT IF(
  (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
      (TABLE_SCHEMA = @dbname)
      AND (TABLE_NAME = @tablename)
      AND (COLUMN_NAME = @column2)
  ) > 0,
  'SELECT "La colonne two_factor_enabled existe déjà." AS message;',
  CONCAT('ALTER TABLE `', @tablename, '` ADD COLUMN `', @column2, '` tinyint(1) NOT NULL DEFAULT 0 COMMENT "2FA activé (1) ou non (0)" AFTER `', @column1, '`;')
));
PREPARE alterIfNotExists2 FROM @preparedStatement2;
EXECUTE alterIfNotExists2;
DEALLOCATE PREPARE alterIfNotExists2;

-- Message de confirmation
SELECT "Migration 017: Ajout des champs 2FA à la table users terminée avec succès." AS message;

