SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_lucky_gift;

-- 将旧 platform/room/gift 三层基础池合并为 app_code + pool_id 的单一基础池。
-- 迁移保留已经存在的 scope_type='pool' 水位，因此脚本可在旧三池删除后的环境重复执行而不改变结果。
DROP TEMPORARY TABLE IF EXISTS lucky_pool_single_merge;

CREATE TEMPORARY TABLE lucky_pool_single_merge AS
SELECT
  app_code,
  pool_id,
  SUM(balance) AS balance,
  SUM(reserve_floor) AS reserve_floor,
  SUM(total_in) AS total_in,
  SUM(total_out) AS total_out,
  MIN(created_at_ms) AS created_at_ms,
  MAX(updated_at_ms) AS updated_at_ms
FROM (
  SELECT
    app_code,
    scope_id AS pool_id,
    balance,
    reserve_floor,
    total_in,
    total_out,
    created_at_ms,
    updated_at_ms
  FROM lucky_pools
  WHERE scope_type = 'pool'

  UNION ALL

  SELECT
    app_code,
    CASE
      WHEN scope_type = 'room' THEN SUBSTRING_INDEX(scope_id, ':', 1)
      ELSE scope_id
    END AS pool_id,
    balance,
    reserve_floor,
    total_in,
    total_out,
    created_at_ms,
    updated_at_ms
  FROM lucky_pools
  WHERE scope_type IN ('platform', 'room', 'gift')
) AS source_pools
WHERE pool_id <> ''
GROUP BY app_code, pool_id;

-- 先删除同一 pool_id 下的新旧池行，再插入汇总结果，避免 ON DUPLICATE 在重跑或半迁移环境里把旧水位重复累加。
DELETE p
FROM lucky_pools p
JOIN lucky_pool_single_merge m
  ON p.app_code = m.app_code
 AND (
      (p.scope_type = 'pool' AND p.scope_id = m.pool_id)
   OR (p.scope_type IN ('platform', 'gift') AND p.scope_id = m.pool_id)
   OR (p.scope_type = 'room' AND SUBSTRING_INDEX(p.scope_id, ':', 1) = m.pool_id)
 );

INSERT INTO lucky_pools (
  app_code, scope_type, scope_id, balance, reserve_floor, total_in, total_out, created_at_ms, updated_at_ms
)
SELECT
  app_code,
  'pool',
  pool_id,
  balance,
  reserve_floor,
  total_in,
  total_out,
  created_at_ms,
  updated_at_ms
FROM lucky_pool_single_merge;

DROP TEMPORARY TABLE IF EXISTS lucky_pool_single_merge;
