-- Yumi Gift Challenge late enable cutoff.
--
-- Performance review:
-- 1. The activity table contains only operator-created activity cycles, not gift events; the
--    one-column ALTER is forced to INSTANT so it cannot fall back to a table copy. MySQL rejects an
--    explicit LOCK clause together with INSTANT; metadata locking is therefore left to INSTANT semantics.
-- 2. The backfill touches only already-enabled activity rows. It preserves the historical behavior
--    for activities that were live before this migration, while every later enable writes NOW(3).
-- 3. Event matching still enters through idx_yumi_gc_activity_window
--    (sys_origin, enabled, start_time, end_time). enabled_time is a residual cutoff over the tiny
--    enabled set, so adding it to that index would only increase write cost without improving lookup.

SET NAMES utf8mb4;

SET @add_enabled_time := IF(
  (SELECT COUNT(*)
   FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE()
     AND TABLE_NAME = 'yumi_gift_challenge_activity'
     AND COLUMN_NAME = 'enabled_time') = 0,
  'ALTER TABLE `yumi_gift_challenge_activity` ADD COLUMN `enabled_time` DATETIME(3) NULL COMMENT ''首次实际启用时间，早于该时间的礼物不回放'', ALGORITHM=INSTANT',
  'SELECT 1'
);
PREPARE add_enabled_time_stmt FROM @add_enabled_time;
EXECUTE add_enabled_time_stmt;
DEALLOCATE PREPARE add_enabled_time_stmt;

UPDATE `yumi_gift_challenge_activity`
SET `enabled_time` = `start_time`
WHERE `enabled` = 1
  AND `enabled_time` IS NULL;
