-- Migration : Ajout des champs manquants dans email_queue
-- Date : 2025-01-06
-- Description : Ajoute sent_at et error_message pour le bon fonctionnement du CRON

USE geo_app;

-- Vérifier si les champs existent déjà avant de les ajouter
SET @db_name = DATABASE();
SET @table_name = 'email_queue';

-- Ajouter sent_at si n'existe pas
SET @column_exists = (
    SELECT COUNT(*)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = @db_name
    AND TABLE_NAME = @table_name
    AND COLUMN_NAME = 'sent_at'
);

SET @sql = IF(@column_exists = 0,
    'ALTER TABLE email_queue ADD COLUMN sent_at TIMESTAMP NULL DEFAULT NULL AFTER status',
    'SELECT "Column sent_at already exists" AS message'
);

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Ajouter error_message si n'existe pas
SET @column_exists = (
    SELECT COUNT(*)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = @db_name
    AND TABLE_NAME = @table_name
    AND COLUMN_NAME = 'error_message'
);

SET @sql = IF(@column_exists = 0,
    'ALTER TABLE email_queue ADD COLUMN error_message TEXT NULL DEFAULT NULL AFTER attempts',
    'SELECT "Column error_message already exists" AS message'
);

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Vérifier le résultat
SELECT
    'Migration terminée' AS status,
    COLUMN_NAME,
    COLUMN_TYPE,
    IS_NULLABLE,
    COLUMN_DEFAULT
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name
AND TABLE_NAME = @table_name
AND COLUMN_NAME IN ('sent_at', 'error_message');
