SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_lucky_gift;

-- 四个新增标量都使用 INSTANT 元数据变更，不扫描用户状态或规则历史。历史 token 不在迁移中
-- 全表 UPDATE：新运行时锁定单用户主键行后发现 version=0/不匹配即清零，避免上线 DDL 后再锁大表。
SET @ddl := IF((SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='lucky_gift_rule_versions' AND COLUMN_NAME='jackpot_rate_limit_window_minutes')=0,
  'ALTER TABLE lucky_gift_rule_versions ADD COLUMN jackpot_rate_limit_window_minutes BIGINT NOT NULL DEFAULT 0 COMMENT ''app+pool 全局滚动爆奖窗口分钟数；0仅兼容历史规则'' AFTER max_jackpot_hits_per_user_day, ALGORITHM=INSTANT',
  'SELECT 1');
PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @ddl := IF((SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='lucky_gift_rule_versions' AND COLUMN_NAME='max_jackpot_hits_per_window')=0,
  'ALTER TABLE lucky_gift_rule_versions ADD COLUMN max_jackpot_hits_per_window BIGINT NOT NULL DEFAULT 0 COMMENT ''全局滚动窗口内两类大奖合计上限；0仅兼容历史规则'' AFTER jackpot_rate_limit_window_minutes, ALGORITHM=INSTANT',
  'SELECT 1');
PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @ddl := IF((SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='lucky_user_states' AND COLUMN_NAME='pending_spend_jackpot_rule_version')=0,
  'ALTER TABLE lucky_user_states ADD COLUMN pending_spend_jackpot_rule_version BIGINT NOT NULL DEFAULT 0 COMMENT ''消费大奖资格所属不可变规则版本；0及版本不匹配均在下一抽安全过期'' AFTER pending_spend_jackpot_tokens, ALGORITHM=INSTANT',
  'SELECT 1');
PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @ddl := IF((SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='lucky_user_strategy_days' AND COLUMN_NAME='spend_rule_version')=0,
  'ALTER TABLE lucky_user_strategy_days ADD COLUMN spend_rule_version BIGINT NOT NULL DEFAULT 0 COMMENT ''spend_coins 所属不可变规则版本；切换版本时从0重新累计'' AFTER spend_coins, ALGORITHM=INSTANT',
  'SELECT 1');
PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- 滚动限制只读取最近 N 分钟的大奖事实。该索引避免 JSON/开奖大表扫描；创建索引会读取
-- lucky_gift_user_jackpot_hits，生产执行前必须检查表大小并安排在低峰，使用 INPLACE/LOCK=NONE 保持写入可用。
SET @ddl := IF((SELECT COUNT(*) FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='lucky_gift_user_jackpot_hits' AND INDEX_NAME='idx_lucky_jackpot_rate_window')=0,
  'ALTER TABLE lucky_gift_user_jackpot_hits ADD KEY idx_lucky_jackpot_rate_window (app_code, pool_id, occurred_at_ms, source_type, source_draw_id), ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1');
PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt;
