-- 房间列表活动图标只读取 room_list_entries 同一行；新增列不参与排序索引，避免放大列表查询成本。
-- MySQL 8 INSTANT 仅修改数据字典；红包 packet 投影是新表，不扫描 room_list_entries 或 wallet 资金表。
SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_room;

DROP PROCEDURE IF EXISTS hyapp_migrate_005_room_list_activity_indicators;

DELIMITER $$

CREATE PROCEDURE hyapp_migrate_005_room_list_activity_indicators()
BEGIN
  IF EXISTS (
    SELECT 1 FROM information_schema.tables
    WHERE table_schema = DATABASE() AND table_name = 'room_list_entries'
  ) THEN
    IF NOT EXISTS (
      SELECT 1 FROM information_schema.columns
      WHERE table_schema = DATABASE() AND table_name = 'room_list_entries' AND column_name = 'rocket_near_completion'
    ) THEN
      ALTER TABLE room_list_entries
        ADD COLUMN rocket_near_completion BOOLEAN NOT NULL DEFAULT FALSE COMMENT '当前档火箭剩余燃料不超过 20%' AFTER sort_score,
        ALGORITHM=INSTANT;
    END IF;
    IF NOT EXISTS (
      SELECT 1 FROM information_schema.columns
      WHERE table_schema = DATABASE() AND table_name = 'room_list_entries' AND column_name = 'has_active_red_packet'
    ) THEN
      ALTER TABLE room_list_entries
        ADD COLUMN has_active_red_packet BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'wallet MQ 派生的房间有效红包聚合' AFTER rocket_near_completion,
        ALGORITHM=INSTANT;
    END IF;
    IF NOT EXISTS (
      SELECT 1 FROM information_schema.columns
      WHERE table_schema = DATABASE() AND table_name = 'room_list_entries' AND column_name = 'active_red_packet_expires_at_ms'
    ) THEN
      ALTER TABLE room_list_entries
        ADD COLUMN active_red_packet_expires_at_ms BIGINT NOT NULL DEFAULT 0 COMMENT '仍有余量红包的最晚到期时间，UTC epoch ms' AFTER has_active_red_packet,
        ALGORITHM=INSTANT;
    END IF;
  END IF;
END$$

CALL hyapp_migrate_005_room_list_activity_indicators()$$
DROP PROCEDURE IF EXISTS hyapp_migrate_005_room_list_activity_indicators$$

DELIMITER ;

CREATE TABLE IF NOT EXISTS room_red_packet_projections (
  app_code VARCHAR(32) NOT NULL COMMENT '应用编码，多租户隔离',
  packet_id VARCHAR(128) NOT NULL COMMENT 'wallet 红包 ID',
  room_id VARCHAR(64) NOT NULL COMMENT '红包所属房间',
  status VARCHAR(32) NOT NULL COMMENT 'wallet 红包状态快照',
  remaining_amount BIGINT NOT NULL DEFAULT 0 COMMENT '事件携带的剩余金额',
  remaining_count INT NOT NULL DEFAULT 0 COMMENT '事件携带的剩余份数',
  expires_at_ms BIGINT NOT NULL DEFAULT 0 COMMENT '红包到期时间，UTC epoch ms',
  event_rank INT NOT NULL DEFAULT 0 COMMENT 'created/claimed/refunded 单调状态级别',
  event_occurred_at_ms BIGINT NOT NULL COMMENT 'wallet 事实发生时间，UTC epoch ms',
  updated_at_ms BIGINT NOT NULL COMMENT '投影更新时间，UTC epoch ms',
  PRIMARY KEY (app_code, packet_id),
  KEY idx_room_red_packet_active (app_code, room_id, status, expires_at_ms)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='红包房间列表异步投影，不承载资金事实';
