SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;
SET time_zone = '+00:00';

USE hyapp_wallet;

-- 工资政策和等级是小型配置表；新增列及索引只触碰配置数据，不扫描周期账户或钱包流水。
-- 结算进度/记录可能持续增长，因此只新增带默认值的审计列并使用在线 DDL，不执行历史全表回填。
SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'host_agency_salary_policies' AND COLUMN_NAME = 'cycle_key') = 0,
  'ALTER TABLE host_agency_salary_policies ADD COLUMN cycle_key VARCHAR(7) NOT NULL DEFAULT '''' COMMENT ''政策归属工资周期，UTC yyyy-MM'' AFTER policy_id, ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'host_agency_salary_policies' AND COLUMN_NAME = 'policy_version') = 0,
  'ALTER TABLE host_agency_salary_policies ADD COLUMN policy_version BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''不可变政策版本，等于后台政策 ID'' AFTER cycle_key, ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 老政策没有显式周期时按原有效期起点归档；起点为 0 的历史行退回创建月份。会话已固定 UTC，避免服务器时区漂移。
UPDATE host_agency_salary_policies
SET cycle_key = DATE_FORMAT(FROM_UNIXTIME(COALESCE(NULLIF(effective_from_ms, 0), created_at_ms) / 1000), '%Y-%m'),
    policy_version = policy_id
WHERE cycle_key = '' OR policy_version = 0;

CREATE TABLE IF NOT EXISTS host_salary_policy_cycle_bindings (
  app_code VARCHAR(32) NOT NULL DEFAULT 'lalu' COMMENT '应用编码，用于多租户隔离',
  region_id BIGINT NOT NULL COMMENT '适用区域 ID',
  cycle_key VARCHAR(7) NOT NULL COMMENT '工资周期键，UTC yyyy-MM',
  policy_id BIGINT UNSIGNED NOT NULL COMMENT '绑定的不可变政策 ID',
  policy_version BIGINT UNSIGNED NOT NULL COMMENT '绑定的不可变政策版本',
  created_at_ms BIGINT NOT NULL COMMENT '首次绑定时间，UTC epoch ms',
  PRIMARY KEY (app_code, region_id, cycle_key),
  UNIQUE KEY uk_host_salary_policy_cycle_version (app_code, policy_id, policy_version)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='主播工资周期不可变政策绑定表';

-- 同一区域同月若存在多条旧快照，只选原查询会命中的最新一条；INSERT IGNORE 保证迁移可重放且不会覆盖既有绑定。
INSERT IGNORE INTO host_salary_policy_cycle_bindings (
  app_code, region_id, cycle_key, policy_id, policy_version, created_at_ms
)
SELECT policy.app_code, policy.region_id, policy.cycle_key, policy.policy_id, policy.policy_version, policy.created_at_ms
FROM host_agency_salary_policies policy
WHERE policy.cycle_key <> ''
  AND policy.status = 'active'
  AND NOT EXISTS (
    SELECT 1
    FROM host_agency_salary_policies newer
    WHERE newer.app_code = policy.app_code
      AND newer.region_id = policy.region_id
      AND newer.cycle_key = policy.cycle_key
      AND newer.status = 'active'
      AND (
        newer.effective_from_ms > policy.effective_from_ms
        OR (newer.effective_from_ms = policy.effective_from_ms AND newer.policy_id > policy.policy_id)
      )
  );

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.STATISTICS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'host_agency_salary_policies' AND INDEX_NAME = 'idx_host_agency_salary_policy_cycle') = 0,
  'ALTER TABLE host_agency_salary_policies ADD INDEX idx_host_agency_salary_policy_cycle (app_code, region_id, cycle_key, status, settlement_mode, settlement_trigger_mode), ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'host_salary_settlement_progress' AND COLUMN_NAME = 'last_policy_version') = 0,
  'ALTER TABLE host_salary_settlement_progress ADD COLUMN last_policy_version BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''最后一次使用的不可变政策版本'' AFTER last_policy_id, ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'host_salary_settlement_records' AND COLUMN_NAME = 'policy_version') = 0,
  'ALTER TABLE host_salary_settlement_records ADD COLUMN policy_version BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''使用的不可变政策版本'' AFTER policy_id, ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
