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

-- 工资政策是小型配置表；这里只补复制来源和月查询索引，不读取工资账户、结算记录或钱包流水。
SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'admin_host_agency_salary_policies' AND COLUMN_NAME = 'copied_from_policy_id') = 0,
  'ALTER TABLE admin_host_agency_salary_policies ADD COLUMN copied_from_policy_id BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''自动复制来源政策 ID'' AFTER published_by_admin_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 = 'admin_host_agency_salary_policies' AND COLUMN_NAME = 'copied_from_cycle_key') = 0,
  'ALTER TABLE admin_host_agency_salary_policies ADD COLUMN copied_from_cycle_key VARCHAR(7) NOT NULL DEFAULT '''' COMMENT ''自动复制来源工资月，UTC yyyy-MM'' AFTER copied_from_policy_id, ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 同名政策允许每月各有一个不可变版本；只在索引唯一性或有序列组成不正确时重建，
-- 正确状态下重复执行迁移不触发 DDL，也不制造短暂的唯一约束空窗。
SET @name_index_signature := (
  SELECT CONCAT(MIN(NON_UNIQUE), ':', GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX SEPARATOR ','))
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'admin_host_agency_salary_policies'
    AND INDEX_NAME = 'uk_admin_host_agency_salary_policy_name'
);
SET @ddl := IF(
  @name_index_signature IS NOT NULL
    AND @name_index_signature <> '0:app_code,region_id,cycle_key,name',
  'ALTER TABLE admin_host_agency_salary_policies DROP INDEX uk_admin_host_agency_salary_policy_name, ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @name_index_signature := (
  SELECT CONCAT(MIN(NON_UNIQUE), ':', GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX SEPARATOR ','))
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'admin_host_agency_salary_policies'
    AND INDEX_NAME = 'uk_admin_host_agency_salary_policy_name'
);
SET @ddl := IF(
  @name_index_signature IS NULL,
  'ALTER TABLE admin_host_agency_salary_policies ADD UNIQUE INDEX uk_admin_host_agency_salary_policy_name (app_code, region_id, cycle_key, name), ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

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