SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

SET @now_ms = CAST(UNIX_TIMESTAMP(UTC_TIMESTAMP(3)) * 1000 AS UNSIGNED);

-- 收益策略模板是 Lalu/Huwaa/Fami 共用的产品配置入口。存量模板显式补 0，避免旧实例重发时产生新分成。
UPDATE admin_policy_templates
SET rule_json = JSON_SET(rule_json, '$.agency.point_ratio_percent', 0),
    updated_at_ms = @now_ms
WHERE template_code = 'first_google70000_coin_seller_92000_100000_v1'
  AND template_version = 'v1'
  AND JSON_EXTRACT(rule_json, '$.agency.point_ratio_percent') IS NULL;

UPDATE admin_policy_template_versions
SET rule_json = JSON_SET(rule_json, '$.agency.point_ratio_percent', 0),
    updated_at_ms = @now_ms
WHERE template_code = 'first_google70000_coin_seller_92000_100000_v1'
  AND template_version = 'v1'
  AND JSON_EXTRACT(rule_json, '$.agency.point_ratio_percent') IS NULL;

-- Fami 从同一份公共政策结构派生独立模板，默认 20%；运营可在 Admin 编辑并发布，不需要改代码。
INSERT INTO admin_policy_templates (
  template_code, template_version, name, status, rule_json, description,
  created_by_admin_id, updated_by_admin_id, created_at_ms, updated_at_ms
)
SELECT
  'fami_guild_revenue_policy', 'v1', 'Fami 公会收益政策', 'active',
  JSON_SET(rule_json, '$.agency.point_ratio_percent', 20),
  'Fami 主播与 Agency POINT 收益政策；Agency 默认 20%，以发布后的运行快照为准。',
  0, 0, @now_ms, @now_ms
FROM admin_policy_templates
WHERE template_code = 'first_google70000_coin_seller_92000_100000_v1' AND template_version = 'v1'
ON DUPLICATE KEY UPDATE
  name = VALUES(name),
  status = VALUES(status),
  description = VALUES(description),
  updated_at_ms = @now_ms;

INSERT INTO admin_policy_template_versions (
  template_code, template_version, status, rule_json,
  created_by_admin_id, updated_by_admin_id, created_at_ms, updated_at_ms
)
SELECT
  template_code, template_version, status, rule_json,
  created_by_admin_id, updated_by_admin_id, created_at_ms, updated_at_ms
FROM admin_policy_templates
WHERE template_code = 'fami_guild_revenue_policy' AND template_version = 'v1'
ON DUPLICATE KEY UPDATE
  status = VALUES(status),
  rule_json = VALUES(rule_json),
  updated_at_ms = @now_ms;

INSERT INTO admin_policy_instances (
  app_code, instance_code, template_code, template_version, region_scope, status,
  effective_from_ms, effective_to_ms, publish_status, created_by_admin_id, updated_by_admin_id,
  created_at_ms, updated_at_ms
) VALUES (
  'fami', 'fami_guild_revenue_policy', 'fami_guild_revenue_policy', 'v1',
  'all_active_regions', 'active', @now_ms, 0, 'draft', 0, 0, @now_ms, @now_ms
)
ON DUPLICATE KEY UPDATE
  template_code = VALUES(template_code),
  template_version = VALUES(template_version),
  region_scope = VALUES(region_scope),
  status = VALUES(status),
  effective_to_ms = VALUES(effective_to_ms),
  updated_at_ms = @now_ms;
