-- Yumi Game King: direct multi-resource rewards and stop/resume settlement safety.
--
-- Performance review:
-- 1. Both ALTERs target bounded configuration/delivery tables; no game-event ledger,
--    wallet ledger or ranking aggregate is scanned.
-- 2. reward_items_json is nullable during the online DDL. The two bounded UPDATE JOINs use
--    owner_type/owner_id and prize/rank primary keys to freeze existing pending orders
--    before operators can change their activity configuration.
-- 3. ever_enabled is backfilled from the indexed enabled flag plus three activity-scoped
--    existence probes. Each probe uses an activity_id primary/index prefix and stops at
--    the first row, avoiding full scans of event or draw history.
-- 4. Run during low traffic with adequate temporary disk. LOCK=NONE keeps ordinary reads
--    and writes available, but MySQL metadata locks can still wait behind long transactions.

ALTER TABLE `yumi_game_king_activity`
  ADD COLUMN `ever_enabled` TINYINT(1) NOT NULL DEFAULT 0 AFTER `enabled`,
  ALGORITHM=INPLACE, LOCK=NONE;

UPDATE `yumi_game_king_activity` AS activity
SET activity.`ever_enabled` = 1
WHERE activity.`enabled` = 1
   OR EXISTS (
     SELECT 1
     FROM `yumi_game_king_user` AS aggregate
     WHERE aggregate.`activity_id` = activity.`id`
     LIMIT 1
   )
   OR EXISTS (
     SELECT 1
     FROM `yumi_game_king_draw_record` AS draw_record
     WHERE draw_record.`activity_id` = activity.`id`
     LIMIT 1
   )
   OR EXISTS (
     SELECT 1
     FROM `yumi_game_king_period_settlement` AS period_gate
     WHERE period_gate.`activity_id` = activity.`id`
     LIMIT 1
   );

ALTER TABLE `yumi_game_king_delivery_item`
  ADD COLUMN `reward_items_json` TEXT NULL AFTER `resource_group_id`,
  ALGORITHM=INPLACE, LOCK=NONE;

UPDATE `yumi_game_king_delivery_item` AS delivery
JOIN `yumi_game_king_draw_record` AS draw_record
  ON delivery.`owner_type` = 'DRAW'
 AND delivery.`owner_id` = draw_record.`id`
JOIN `yumi_game_king_prize` AS prize
  ON prize.`id` = draw_record.`prize_id`
SET delivery.`reward_items_json` = prize.`reward_items_json`
WHERE delivery.`reward_items_json` IS NULL;

UPDATE `yumi_game_king_delivery_item` AS delivery
JOIN `yumi_game_king_settlement_record` AS settlement
  ON delivery.`owner_type` = 'SETTLEMENT'
 AND delivery.`owner_id` = settlement.`id`
JOIN `yumi_game_king_rank_reward` AS rank_reward
  ON rank_reward.`id` = settlement.`rank_reward_id`
SET delivery.`reward_items_json` = rank_reward.`reward_items_json`
WHERE delivery.`reward_items_json` IS NULL;
