SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_activity;

-- 所有新增列都使用 INSTANT 元数据变更，不扫描或重写高频事件/进度表。历史全局配置回填 0 后继续作为
-- 全区域默认配置，具体区域配置存在时由业务查询优先命中具体区域。
ALTER TABLE room_turnover_reward_configs
  ADD COLUMN region_id BIGINT NOT NULL DEFAULT 0 COMMENT '配置区域 ID；0 表示全区域默认配置', ALGORITHM=INSTANT;
ALTER TABLE room_turnover_reward_tiers
  ADD COLUMN region_id BIGINT NOT NULL DEFAULT 0 COMMENT '配置区域 ID；0 表示全区域默认配置', ALGORITHM=INSTANT;
ALTER TABLE room_turnover_reward_event_consumption
  ADD COLUMN region_id BIGINT NOT NULL DEFAULT 0 COMMENT '事件发生时房间区域 ID', ALGORITHM=INSTANT;
ALTER TABLE room_turnover_reward_progress
  ADD COLUMN region_id BIGINT NOT NULL DEFAULT 0 COMMENT '事件发生时房间区域 ID', ALGORITHM=INSTANT;
ALTER TABLE room_turnover_reward_settlements
  ADD COLUMN region_id BIGINT NOT NULL DEFAULT 0 COMMENT '结算对应房间区域 ID', ALGORITHM=INSTANT;
ALTER TABLE agency_opening_cycles
  ADD COLUMN region_id BIGINT NOT NULL DEFAULT 0 COMMENT '配置区域 ID；0 表示全区域默认活动', ALGORITHM=INSTANT;
ALTER TABLE agency_opening_applications
  ADD COLUMN region_id BIGINT NOT NULL DEFAULT 0 COMMENT '申请时代理区域 ID', ALGORITHM=INSTANT;
ALTER TABLE agency_opening_score_events
  ADD COLUMN region_id BIGINT NOT NULL DEFAULT 0 COMMENT '事件发生时房间区域 ID', ALGORITHM=INSTANT;

-- 业务唯一键必须携带 region_id，保证同一 App 的不同区域可独立配置和结算。
-- 这些索引变更需要扫描索引记录，但使用 INPLACE + LOCK=NONE，部署前仍应按线上表体量确认 DDL 时长和磁盘余量。
ALTER TABLE room_turnover_reward_configs
  DROP PRIMARY KEY,
  ADD PRIMARY KEY (app_code, region_id),
  ALGORITHM=INPLACE, LOCK=NONE;
ALTER TABLE room_turnover_reward_tiers
  DROP INDEX uk_room_turnover_reward_tier_code,
  DROP INDEX idx_room_turnover_reward_tiers_match,
  ADD UNIQUE KEY uk_room_turnover_reward_tier_code (app_code, region_id, tier_code),
  ADD KEY idx_room_turnover_reward_tiers_match (app_code, region_id, status, threshold_coin_spent),
  ALGORITHM=INPLACE, LOCK=NONE;
ALTER TABLE room_turnover_reward_progress
  DROP PRIMARY KEY,
  ADD PRIMARY KEY (app_code, region_id, room_id, period_start_ms),
  ALGORITHM=INPLACE, LOCK=NONE;
ALTER TABLE room_turnover_reward_settlements
  DROP INDEX uk_room_turnover_reward_settlement_room_period,
  ADD UNIQUE KEY uk_room_turnover_reward_settlement_room_period (app_code, region_id, room_id, period_start_ms),
  ADD KEY idx_room_turnover_reward_settlement_region (app_code, region_id, period_start_ms, created_at_ms),
  ALGORITHM=INPLACE, LOCK=NONE;
ALTER TABLE agency_opening_cycles
  DROP INDEX idx_agency_opening_cycle_current,
  ADD KEY idx_agency_opening_cycle_current (app_code, region_id, activity_code, status, start_ms, end_ms),
  ALGORITHM=INPLACE, LOCK=NONE;
ALTER TABLE agency_opening_applications
  ADD KEY idx_agency_opening_application_region (app_code, region_id, updated_at_ms, application_id),
  ALGORITHM=INPLACE, LOCK=NONE;
