-- Yumi Game King: configurable DAILY Top1/Top2/Top3 rewards and idempotent daily settlement.
--
-- Performance review:
-- 1. rank_reward and settlement_record are bounded configuration/result tables. Their index
--    rebuilds do not scan the high-volume game-event ledger or task archive.
-- 2. Existing settlement rows are marked OVERALL by constant defaults; no aggregate backfill
--    or ranking sort is executed by this migration.
-- 3. The new period gate has one row per activity day. Its due-status index supports bounded
--    cron discovery, while the unique activity/date key makes repeated cron calls idempotent.
-- 4. Run the two ALTER statements during low traffic. LOCK=NONE keeps reads/writes available,
--    but MySQL still needs temporary space to rebuild the small secondary indexes.

ALTER TABLE `yumi_game_king_rank_reward`
  DROP INDEX `uk_yumi_gk_rank_range`,
  DROP INDEX `idx_yumi_gk_rank_start`,
  ADD COLUMN `ranking_period` VARCHAR(32) NOT NULL DEFAULT 'OVERALL' AFTER `ranking_type`,
  ADD UNIQUE KEY `uk_yumi_gk_rank_range` (
    `activity_id`, `ranking_period`, `ranking_type`, `start_rank`, `end_rank`
  ),
  ADD KEY `idx_yumi_gk_rank_start` (
    `activity_id`, `ranking_period`, `ranking_type`, `start_rank`
  ),
  ALGORITHM=INPLACE, LOCK=NONE;

ALTER TABLE `yumi_game_king_settlement_record`
  DROP INDEX `uk_yumi_gk_settle_user`,
  DROP INDEX `uk_yumi_gk_settle_rank`,
  DROP INDEX `idx_yumi_gk_settle_status`,
  ADD COLUMN `ranking_period` VARCHAR(32) NOT NULL DEFAULT 'OVERALL' AFTER `ranking_type`,
  ADD COLUMN `period_key` VARCHAR(32) NOT NULL DEFAULT 'OVERALL' AFTER `ranking_period`,
  ADD COLUMN `stat_date` DATE NULL AFTER `period_key`,
  ADD UNIQUE KEY `uk_yumi_gk_settle_user` (
    `activity_id`, `period_key`, `ranking_type`, `user_id`
  ),
  ADD UNIQUE KEY `uk_yumi_gk_settle_rank` (
    `activity_id`, `period_key`, `ranking_type`, `rank_no`
  ),
  ADD KEY `idx_yumi_gk_settle_status` (
    `activity_id`, `ranking_period`, `period_key`, `delivery_status`
  ),
  ALGORITHM=INPLACE, LOCK=NONE;

CREATE TABLE IF NOT EXISTS `yumi_game_king_period_settlement` (
  `id` BIGINT NOT NULL,
  `activity_id` BIGINT NOT NULL,
  `period_type` VARCHAR(32) NOT NULL DEFAULT 'DAILY',
  `period_key` VARCHAR(32) NOT NULL,
  `stat_date` DATE NOT NULL,
  `snapshot_due_time` DATETIME(3) NOT NULL,
  `status` VARCHAR(32) NOT NULL DEFAULT 'PROCESSING',
  `create_time` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `update_time` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_yumi_gk_period` (`activity_id`, `period_type`, `period_key`),
  KEY `idx_yumi_gk_period_due` (`status`, `snapshot_due_time`, `id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Daily Game King settlement gate including empty ranking days';
