SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- Databi 留存查询会按注册日 cohort 读取 stat_user_registration，并可叠加国家或区域筛选。
-- 这两个索引只用于老库受控补齐：请在低峰执行，并在执行后对留存 SQL 做 EXPLAIN。
-- 不放进服务启动自动迁移，避免大表普通 ALTER 在生产启动时造成元数据锁或 IO 峰值。

SET @add_retention_country_day := (
  SELECT IF(
    COUNT(*) = 0,
    'ALTER TABLE stat_user_registration ADD INDEX idx_stat_user_registration_country_day (app_code, stat_tz, country_id, registered_day, user_id), ALGORITHM=INPLACE, LOCK=NONE',
    'SELECT 1'
  )
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'stat_user_registration'
    AND INDEX_NAME = 'idx_stat_user_registration_country_day'
);

PREPARE stmt FROM @add_retention_country_day;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @add_retention_region_day := (
  SELECT IF(
    COUNT(*) = 0,
    'ALTER TABLE stat_user_registration ADD INDEX idx_stat_user_registration_region_day (app_code, stat_tz, region_id, registered_day, country_id, user_id), ALGORITHM=INPLACE, LOCK=NONE',
    'SELECT 1'
  )
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'stat_user_registration'
    AND INDEX_NAME = 'idx_stat_user_registration_region_day'
);

PREPARE stmt FROM @add_retention_region_day;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT
  COUNT(*) AS retention_registration_filter_index_count
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
  AND TABLE_NAME = 'stat_user_registration'
  AND INDEX_NAME IN (
    'idx_stat_user_registration_country_day',
    'idx_stat_user_registration_region_day'
  );
