SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_user;

-- 单列追加在 MySQL 8 上使用 INSTANT 元数据变更，不重写 user_cp_applications 大表。
-- 默认 0 明确表示历史行没有精确 wallet 礼物金币价值；禁止用 gift_value 热度值回填。
SET @cp_application_gift_coin_value_exists = (
  SELECT COUNT(*)
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'user_cp_applications'
    AND COLUMN_NAME = 'gift_coin_value'
);
SET @cp_application_gift_coin_value_ddl = IF(
  @cp_application_gift_coin_value_exists = 0,
  'ALTER TABLE user_cp_applications ADD COLUMN gift_coin_value BIGINT NOT NULL DEFAULT 0 COMMENT ''触发申请时 wallet 结算出的礼物金币价值；历史缺失时保持 0'' AFTER gift_value, ALGORITHM=INSTANT',
  'SELECT 1'
);
PREPARE cp_application_gift_coin_value_stmt FROM @cp_application_gift_coin_value_ddl;
EXECUTE cp_application_gift_coin_value_stmt;
DEALLOCATE PREPARE cp_application_gift_coin_value_stmt;

-- 固定资格列让无命中场景走 eligible=1 的空索引范围；历史默认 0，不扫描也不把热度误当金币回填。
SET @cp_application_formation_feed_eligible_exists = (
  SELECT COUNT(*)
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'user_cp_applications'
    AND COLUMN_NAME = 'formation_feed_eligible'
);
SET @cp_application_formation_feed_eligible_ddl = IF(
  @cp_application_formation_feed_eligible_exists = 0,
  'ALTER TABLE user_cp_applications ADD COLUMN formation_feed_eligible TINYINT(1) NOT NULL DEFAULT 0 COMMENT ''成立礼物 feed 固定资格：金币价值严格大于 5000'' AFTER gift_coin_value, ALGORITHM=INSTANT',
  'SELECT 1'
);
PREPARE cp_application_formation_feed_eligible_stmt FROM @cp_application_formation_feed_eligible_ddl;
EXECUTE cp_application_formation_feed_eligible_stmt;
DEALLOCATE PREPARE cp_application_formation_feed_eligible_stmt;

-- feed 从 eligible=1 的 accepted CP 申请按决定时间倒序扫描；等值前缀同时避免全表扫描与全表排序。
-- 在线新增索引仍会扫描整张申请表并消耗 IO/临时空间，生产执行应安排低峰并先确认磁盘余量。
SET @cp_application_formation_feed_index_exists = (
  SELECT COUNT(*)
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'user_cp_applications'
    AND INDEX_NAME = 'idx_user_cp_app_formation_feed'
);
SET @cp_application_formation_feed_index_ddl = IF(
  @cp_application_formation_feed_index_exists = 0,
  'ALTER TABLE user_cp_applications ADD INDEX idx_user_cp_app_formation_feed (app_code, status, relation_type, formation_feed_eligible, decided_at_ms, application_id), ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);
PREPARE cp_application_formation_feed_index_stmt FROM @cp_application_formation_feed_index_ddl;
EXECUTE cp_application_formation_feed_index_stmt;
DEALLOCATE PREPARE cp_application_formation_feed_index_stmt;
