-- 1.0.346 S1 看板重算进度字段与租户级锁。
SET NAMES utf8mb4;

SET @ddl := (
  SELECT IF(
    EXISTS(SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='ado_s1_dashboard_rebuild_job' AND COLUMN_NAME='current_stage'),
    'SELECT 1',
    'ALTER TABLE `ado_s1_dashboard_rebuild_job`
      ADD COLUMN `current_stage` VARCHAR(32) NOT NULL DEFAULT ''QUEUED'' AFTER `atomic_rows`,
      ADD COLUMN `stage_index` TINYINT NOT NULL DEFAULT 0 AFTER `current_stage`,
      ADD COLUMN `stage_total` TINYINT NOT NULL DEFAULT 5 AFTER `stage_index`,
      ADD COLUMN `progress_percent` TINYINT NOT NULL DEFAULT 0 AFTER `stage_total`,
      ADD COLUMN `progress_message` VARCHAR(255) NULL AFTER `progress_percent`,
      ADD COLUMN `last_progress_at` DATETIME(3) NULL AFTER `progress_message`,
      ADD COLUMN `failed_stage` VARCHAR(32) NULL AFTER `last_progress_at`'
  )
);
PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt;

UPDATE `ado_s1_dashboard_rebuild_job`
SET `current_stage`='QUEUED', `progress_percent`=0, `stage_index`=0, `stage_total`=5
WHERE `status`='QUEUED' AND (`current_stage` IS NULL OR `current_stage`='QUEUED') AND `progress_percent`=0;

UPDATE `ado_s1_dashboard_rebuild_job`
SET `current_stage`='PREPARING', `progress_percent`=5, `stage_total`=5
WHERE `status`='RUNNING' AND (`current_stage` IS NULL OR `current_stage` IN ('QUEUED',''));

UPDATE `ado_s1_dashboard_rebuild_job`
SET `current_stage`='SUCCESS', `progress_percent`=100, `stage_index`=5, `stage_total`=5
WHERE `status`='SUCCESS';

UPDATE `ado_s1_dashboard_rebuild_job`
SET `current_stage`='FAILED', `stage_total`=5
WHERE `status`='FAILED' AND (`current_stage` IS NULL OR `current_stage`='');

UPDATE `ado_s1_dashboard_rebuild_job`
SET `current_stage`='CANCELLED', `stage_total`=5
WHERE `status`='CANCELLED' AND (`current_stage` IS NULL OR `current_stage`='');

SET @ddl := (
  SELECT IF(
    EXISTS(SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='ado_s1_dashboard_rebuild_job' AND INDEX_NAME='ix_s1_rebuild_scope'),
    'SELECT 1',
    'ALTER TABLE `ado_s1_dashboard_rebuild_job` ADD KEY `ix_s1_rebuild_scope` (`tenant_id`, `factory_id`, `status`, `submitted_at`)'
  )
);
PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt;

UPDATE `ado_s1_mdp_run_lock`
SET `status`='FREE', `holder_id`=NULL, `job_id`=NULL
WHERE `lock_name`='S1_MDP_FULL'
  AND (`status`='FREE' OR `heartbeat_at` IS NULL OR `heartbeat_at` < DATE_SUB(NOW(), INTERVAL 30 MINUTE));
