-- MSIN-4328 — Config sync automatique (phase A : stockage + UI, pas encore de cron)
-- Prérequis : sql/MSIN-4328-chronotrack-last-push-at.sql
-- Idempotent.

SET @db := DATABASE();

SET @col_ase := (
    SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'api_chronotrack_config' AND COLUMN_NAME = 'auto_sync_enabled'
);
SET @sql_ase := IF(
    @col_ase = 0,
    'ALTER TABLE api_chronotrack_config ADD COLUMN auto_sync_enabled TINYINT(1) NOT NULL DEFAULT 0 COMMENT ''MSIN-4328 — sync auto ON/OFF'' AFTER last_push_ok_count',
    'SELECT ''auto_sync_enabled already exists'' AS note'
);
PREPARE stmt_ase FROM @sql_ase;
EXECUTE stmt_ase;
DEALLOCATE PREPARE stmt_ase;

SET @col_asi := (
    SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'api_chronotrack_config' AND COLUMN_NAME = 'auto_sync_interval_min'
);
SET @sql_asi := IF(
    @col_asi = 0,
    'ALTER TABLE api_chronotrack_config ADD COLUMN auto_sync_interval_min SMALLINT UNSIGNED NOT NULL DEFAULT 15 COMMENT ''MSIN-4328 — fréquence minutes'' AFTER auto_sync_enabled',
    'SELECT ''auto_sync_interval_min already exists'' AS note'
);
PREPARE stmt_asi FROM @sql_asi;
EXECUTE stmt_asi;
DEALLOCATE PREPARE stmt_asi;

SET @col_asu := (
    SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'api_chronotrack_config' AND COLUMN_NAME = 'auto_sync_until'
);
SET @sql_asu := IF(
    @col_asu = 0,
    'ALTER TABLE api_chronotrack_config ADD COLUMN auto_sync_until DATETIME NULL DEFAULT NULL COMMENT ''MSIN-4328 — arrêt auto (date+heure)'' AFTER auto_sync_interval_min',
    'SELECT ''auto_sync_until already exists'' AS note'
);
PREPARE stmt_asu FROM @sql_asu;
EXECUTE stmt_asu;
DEALLOCATE PREPARE stmt_asu;

SET @col_lar := (
    SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'api_chronotrack_config' AND COLUMN_NAME = 'last_auto_run_at'
);
SET @sql_lar := IF(
    @col_lar = 0,
    'ALTER TABLE api_chronotrack_config ADD COLUMN last_auto_run_at DATETIME NULL DEFAULT NULL COMMENT ''MSIN-4328 — dernier passage cron (phase B)'' AFTER auto_sync_until',
    'SELECT ''last_auto_run_at already exists'' AS note'
);
PREPARE stmt_lar FROM @sql_lar;
EXECUTE stmt_lar;
DEALLOCATE PREPARE stmt_lar;
