SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 生产切流迁移：把 activity-service 旧幸运礼物 owner 数据复制到 lucky-gift-service 新 owner 库。
-- 该脚本只迁当前线上确认在用的 lalu/lucky 与 lalu/super_lucky；其他 app/pool 需要先确认规则和资金归属后再扩展参数。
-- 迁移必须在 room/gateway 切到 lucky-gift-service 之前执行，避免新服务启动后看不到规则、水位和用户阶段。

SET @lucky_import_app_code := 'lalu';

CREATE DATABASE IF NOT EXISTS hyapp_lucky_gift DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_lucky_gift;

INSERT INTO hyapp_lucky_gift.activities (
  app_code, activity_id, status, updated_at_ms
)
SELECT app_code, activity_id, status, updated_at_ms
FROM hyapp_activity.activities
WHERE app_code = @lucky_import_app_code
  AND activity_id IN ('lucky_gift', 'lucky-gift', 'lucky', 'super_lucky')
ON DUPLICATE KEY UPDATE
  status = VALUES(status),
  updated_at_ms = VALUES(updated_at_ms);

INSERT INTO hyapp_lucky_gift.lucky_gift_rule_versions (
  app_code, pool_id, rule_version, enabled, target_rtp_ppm, pool_rate_ppm,
  settlement_window_wager, control_band_ppm, gift_price_reference,
  novice_max_equivalent_draws, normal_max_equivalent_draws,
  effective_from_ms, created_by_admin_id, created_at_ms
)
SELECT
  app_code, pool_id, rule_version, enabled, target_rtp_ppm, pool_rate_ppm,
  settlement_window_wager, control_band_ppm, gift_price_reference,
  novice_max_equivalent_draws, normal_max_equivalent_draws,
  effective_from_ms, created_by_admin_id, created_at_ms
FROM hyapp_activity.lucky_gift_rule_versions
WHERE app_code = @lucky_import_app_code
  AND pool_id IN ('lucky', 'super_lucky')
ON DUPLICATE KEY UPDATE
  enabled = VALUES(enabled),
  target_rtp_ppm = VALUES(target_rtp_ppm),
  pool_rate_ppm = VALUES(pool_rate_ppm),
  settlement_window_wager = VALUES(settlement_window_wager),
  control_band_ppm = VALUES(control_band_ppm),
  gift_price_reference = VALUES(gift_price_reference),
  novice_max_equivalent_draws = VALUES(novice_max_equivalent_draws),
  normal_max_equivalent_draws = VALUES(normal_max_equivalent_draws),
  effective_from_ms = VALUES(effective_from_ms),
  created_by_admin_id = VALUES(created_by_admin_id),
  created_at_ms = VALUES(created_at_ms);

INSERT INTO hyapp_lucky_gift.lucky_gift_stage_tiers (
  app_code, pool_id, rule_version, stage, tier_id,
  multiplier_ppm, base_weight_ppm, high_water_only, enabled
)
SELECT
  app_code, pool_id, rule_version, stage, tier_id,
  multiplier_ppm, base_weight_ppm, high_water_only, enabled
FROM hyapp_activity.lucky_gift_stage_tiers
WHERE app_code = @lucky_import_app_code
  AND pool_id IN ('lucky', 'super_lucky')
ON DUPLICATE KEY UPDATE
  multiplier_ppm = VALUES(multiplier_ppm),
  base_weight_ppm = VALUES(base_weight_ppm),
  high_water_only = VALUES(high_water_only),
  enabled = VALUES(enabled);

INSERT INTO hyapp_lucky_gift.lucky_rtp_windows (
  app_code, scope_type, scope_id, window_index, target_rtp_ppm, control_window_draws,
  paid_draws, wager_coins, target_payout_coins, actual_base_payout_coins,
  carry_ppm, status, created_at_ms, updated_at_ms
)
SELECT
  app_code, scope_type, scope_id, window_index, target_rtp_ppm, control_window_draws,
  paid_draws, wager_coins, target_payout_coins, actual_base_payout_coins,
  carry_ppm, status, created_at_ms, updated_at_ms
FROM hyapp_activity.lucky_rtp_windows
WHERE app_code = @lucky_import_app_code
  AND scope_type IN ('pool_gift', 'gift', 'global')
  AND (
    scope_id IN ('global', 'lucky', 'super_lucky')
    OR SUBSTRING_INDEX(scope_id, ':v', 1) IN ('lucky', 'super_lucky')
  )
ON DUPLICATE KEY UPDATE
  target_rtp_ppm = VALUES(target_rtp_ppm),
  control_window_draws = VALUES(control_window_draws),
  paid_draws = VALUES(paid_draws),
  wager_coins = VALUES(wager_coins),
  target_payout_coins = VALUES(target_payout_coins),
  actual_base_payout_coins = VALUES(actual_base_payout_coins),
  carry_ppm = VALUES(carry_ppm),
  status = VALUES(status),
  updated_at_ms = VALUES(updated_at_ms);

DROP TEMPORARY TABLE IF EXISTS lucky_import_single_pools;

CREATE TEMPORARY TABLE lucky_import_single_pools 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,
    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 hyapp_activity.lucky_pools
  WHERE app_code = @lucky_import_app_code
    AND (
      (scope_type IN ('platform', 'gift', 'pool') AND scope_id IN ('lucky', 'super_lucky'))
      OR (scope_type = 'room' AND SUBSTRING_INDEX(scope_id, ':', 1) IN ('lucky', 'super_lucky'))
    )
) AS source_pools
GROUP BY app_code, pool_id;

INSERT INTO hyapp_lucky_gift.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_import_single_pools
ON DUPLICATE KEY UPDATE
  balance = VALUES(balance),
  reserve_floor = VALUES(reserve_floor),
  total_in = VALUES(total_in),
  total_out = VALUES(total_out),
  created_at_ms = LEAST(lucky_pools.created_at_ms, VALUES(created_at_ms)),
  updated_at_ms = GREATEST(lucky_pools.updated_at_ms, VALUES(updated_at_ms));

DROP TEMPORARY TABLE IF EXISTS lucky_import_single_pools;

INSERT INTO hyapp_lucky_gift.lucky_user_states (
  app_code, user_id, gift_id, paid_draws, cumulative_wager_coins,
  equivalent_draws, loss_streak, created_at_ms, updated_at_ms
)
SELECT
  app_code, user_id, gift_id, paid_draws, cumulative_wager_coins,
  equivalent_draws, loss_streak, created_at_ms, updated_at_ms
FROM hyapp_activity.lucky_user_states
WHERE app_code = @lucky_import_app_code
  AND gift_id IN ('lucky', 'super_lucky')
ON DUPLICATE KEY UPDATE
  paid_draws = VALUES(paid_draws),
  cumulative_wager_coins = VALUES(cumulative_wager_coins),
  equivalent_draws = VALUES(equivalent_draws),
  loss_streak = VALUES(loss_streak),
  updated_at_ms = VALUES(updated_at_ms);

INSERT IGNORE INTO hyapp_lucky_gift.lucky_draw_records (
  app_code, draw_id, command_id, user_id, device_id, room_id, anchor_id, visible_region_id, pool_id, gift_id,
  coin_spent, rule_version, experience_pool, rtp_window_index, gift_rtp_window_index, selected_tier_id,
  base_reward_coins, effective_reward_coins, stage_feedback, high_multiplier, candidate_tiers_json,
  pool_snapshot_json, rtp_snapshot_json, reward_status, reward_transaction_id, reward_failure_reason,
  paid_at_ms, created_at_ms, updated_at_ms
)
SELECT
  app_code, draw_id, command_id, user_id, device_id, room_id, anchor_id, visible_region_id, pool_id, gift_id,
  coin_spent, rule_version, experience_pool, rtp_window_index, gift_rtp_window_index, selected_tier_id,
  base_reward_coins, effective_reward_coins, stage_feedback, high_multiplier,
  COALESCE(candidate_tiers_json, JSON_OBJECT()),
  COALESCE(pool_snapshot_json, JSON_OBJECT()),
  COALESCE(rtp_snapshot_json, JSON_OBJECT()),
  reward_status, reward_transaction_id, reward_failure_reason,
  paid_at_ms, created_at_ms, updated_at_ms
FROM hyapp_activity.lucky_draw_records
WHERE app_code = @lucky_import_app_code
  AND pool_id IN ('lucky', 'super_lucky');

INSERT INTO hyapp_lucky_gift.lucky_draw_pool_stats (
  app_code, pool_id, gift_id, total_draws, unique_users, unique_rooms, total_spent_coins,
  total_reward_coins, base_reward_coins, pending_draws, granted_draws, failed_draws,
  created_at_ms, updated_at_ms
)
SELECT
  app_code, pool_id, gift_id, total_draws, unique_users, unique_rooms, total_spent_coins,
  total_reward_coins, base_reward_coins, pending_draws, granted_draws, failed_draws,
  created_at_ms, updated_at_ms
FROM hyapp_activity.lucky_draw_pool_stats
WHERE app_code = @lucky_import_app_code
  AND pool_id IN ('lucky', 'super_lucky')
ON DUPLICATE KEY UPDATE
  total_draws = VALUES(total_draws),
  unique_users = VALUES(unique_users),
  unique_rooms = VALUES(unique_rooms),
  total_spent_coins = VALUES(total_spent_coins),
  total_reward_coins = VALUES(total_reward_coins),
  base_reward_coins = VALUES(base_reward_coins),
  pending_draws = VALUES(pending_draws),
  granted_draws = VALUES(granted_draws),
  failed_draws = VALUES(failed_draws),
  updated_at_ms = VALUES(updated_at_ms);

INSERT INTO hyapp_lucky_gift.lucky_draw_pool_day_stats (
  app_code, stat_day, visible_region_id, pool_id, gift_id, draw_count,
  turnover_coin, payout_coin, base_reward_coin, created_at_ms, updated_at_ms
)
SELECT
  app_code, stat_day, visible_region_id, pool_id, gift_id, draw_count,
  turnover_coin, payout_coin, base_reward_coin, created_at_ms, updated_at_ms
FROM hyapp_activity.lucky_draw_pool_day_stats
WHERE app_code = @lucky_import_app_code
  AND pool_id IN ('lucky', 'super_lucky')
ON DUPLICATE KEY UPDATE
  draw_count = VALUES(draw_count),
  turnover_coin = VALUES(turnover_coin),
  payout_coin = VALUES(payout_coin),
  base_reward_coin = VALUES(base_reward_coin),
  updated_at_ms = VALUES(updated_at_ms);

INSERT IGNORE INTO hyapp_lucky_gift.lucky_draw_pool_stat_users (
  app_code, pool_id, gift_id, user_id, created_at_ms
)
SELECT app_code, pool_id, gift_id, user_id, created_at_ms
FROM hyapp_activity.lucky_draw_pool_stat_users
WHERE app_code = @lucky_import_app_code
  AND pool_id IN ('lucky', 'super_lucky');

INSERT IGNORE INTO hyapp_lucky_gift.lucky_draw_pool_stat_rooms (
  app_code, pool_id, gift_id, room_id, created_at_ms
)
SELECT app_code, pool_id, gift_id, room_id, created_at_ms
FROM hyapp_activity.lucky_draw_pool_stat_rooms
WHERE app_code = @lucky_import_app_code
  AND pool_id IN ('lucky', 'super_lucky');

INSERT INTO hyapp_lucky_gift.lucky_draw_pool_stat_cursors (
  app_code, cursor_name, last_draw_created_at_ms, last_draw_id, created_at_ms, updated_at_ms
)
SELECT app_code, cursor_name, last_draw_created_at_ms, last_draw_id, created_at_ms, updated_at_ms
FROM hyapp_activity.lucky_draw_pool_stat_cursors
WHERE app_code = @lucky_import_app_code
ON DUPLICATE KEY UPDATE
  last_draw_created_at_ms = VALUES(last_draw_created_at_ms),
  last_draw_id = VALUES(last_draw_id),
  updated_at_ms = VALUES(updated_at_ms);

INSERT IGNORE INTO hyapp_lucky_gift.lucky_gift_outbox (
  app_code, outbox_id, event_type, payload, status, retry_count, next_retry_at_ms,
  locked_by, lock_until_ms, last_error, created_at_ms, updated_at_ms
)
SELECT
  app_code,
  outbox_id,
  event_type,
  payload,
  CASE WHEN status = 'delivering' THEN 'retryable' ELSE status END,
  retry_count,
  next_retry_at_ms,
  '',
  0,
  last_error,
  created_at_ms,
  updated_at_ms
FROM hyapp_activity.activity_outbox
WHERE app_code = @lucky_import_app_code
  AND event_type IN ('LuckyGiftRewardSettlement', 'LuckyGiftDrawn')
  AND status IN ('pending', 'retryable', 'delivering', 'failed');

-- 验证结果直接返回给执行端；这里只输出汇总，不输出任何连接串或密钥。
SELECT 'rule_versions' AS item, COUNT(*) AS value
FROM hyapp_lucky_gift.lucky_gift_rule_versions
WHERE app_code = @lucky_import_app_code AND pool_id IN ('lucky', 'super_lucky')
UNION ALL
SELECT 'stage_tiers', COUNT(*)
FROM hyapp_lucky_gift.lucky_gift_stage_tiers
WHERE app_code = @lucky_import_app_code AND pool_id IN ('lucky', 'super_lucky')
UNION ALL
SELECT 'single_pools', COUNT(*)
FROM hyapp_lucky_gift.lucky_pools
WHERE app_code = @lucky_import_app_code AND scope_type = 'pool' AND scope_id IN ('lucky', 'super_lucky')
UNION ALL
SELECT 'draw_records', COUNT(*)
FROM hyapp_lucky_gift.lucky_draw_records
WHERE app_code = @lucky_import_app_code AND pool_id IN ('lucky', 'super_lucky')
UNION ALL
SELECT 'pending_outbox', COUNT(*)
FROM hyapp_lucky_gift.lucky_gift_outbox
WHERE app_code = @lucky_import_app_code;
