SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 多区域映射只包含政策配置小表；主表保留 region_id 作为旧索引和旧客户端的首个区域兼容值。
CREATE TABLE IF NOT EXISTS admin_host_agency_salary_policy_regions (
  policy_id BIGINT UNSIGNED NOT NULL COMMENT '工资政策 ID',
  region_id BIGINT NOT NULL COMMENT '适用区域 ID',
  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
  PRIMARY KEY (policy_id, region_id),
  KEY idx_host_agency_policy_region (region_id, policy_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='主播代理工资政策多区域关联表';

-- 旧单区域政策逐行补一条映射；主键让重复执行幂等，且不扫描工资账户、结算或钱包流水大表。
INSERT IGNORE INTO admin_host_agency_salary_policy_regions (policy_id, region_id, created_at_ms)
SELECT id, region_id, created_at_ms
FROM admin_host_agency_salary_policies
WHERE region_id > 0;

-- 多区域映射允许一份政策覆盖多个区域；本占位表用业务主键把 active 唯一性下沉到 MySQL，
-- 从而让并发新增、编辑和自动月复制不能同时占用同一 App/区域/月。表中只保存政策配置占位，不读取工资或钱包流水。
CREATE TABLE IF NOT EXISTS admin_host_agency_salary_policy_active_scopes (
  app_code VARCHAR(32) NOT NULL 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',
  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
  PRIMARY KEY (app_code, region_id, cycle_key),
  KEY idx_host_agency_salary_policy_active_scope_policy (policy_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='启用工资政策区域月份占位表';

-- 同一政策的已有占位在重跑时跳过；若历史数据已经存在两个 active 政策覆盖同一区域/月，
-- 主键冲突会让整条回填原子失败，要求先清理冲突，不能用 INSERT IGNORE 随机选择一份口径。
INSERT INTO admin_host_agency_salary_policy_active_scopes (
  app_code, region_id, cycle_key, policy_id, created_at_ms, updated_at_ms
)
SELECT policy.app_code, policy_region.region_id, policy.cycle_key, policy.id,
       policy.created_at_ms, policy.updated_at_ms
FROM admin_host_agency_salary_policies policy
JOIN admin_host_agency_salary_policy_regions policy_region ON policy_region.policy_id = policy.id
WHERE policy.status = 'active'
  AND NOT EXISTS (
    SELECT 1
    FROM admin_host_agency_salary_policy_active_scopes active_scope
    WHERE active_scope.app_code = policy.app_code
      AND active_scope.region_id = policy_region.region_id
      AND active_scope.cycle_key = policy.cycle_key
      AND active_scope.policy_id = policy.id
  );
