#!/usr/bin/env bash
set -euo pipefail

# 清理本地 Docker MySQL 的幸运礼物运行态数据，不删除后台发布的 lucky_gift_rule_versions / stage_tiers。
# 常用：
#   APP_CODE=lalu ./tools/reset-lucky-gift-local-data.sh
#   APP_CODE=lalu USER_ID=123456 POOL_ID=lucky_100 ./tools/reset-lucky-gift-local-data.sh

APP_CODE="${APP_CODE:-lalu}"
USER_ID="${USER_ID:-}"
POOL_ID="${POOL_ID:-}"
RESET_SHARED="${RESET_SHARED:-1}"
MYSQL_CONTAINER="${MYSQL_CONTAINER:-hyapp-mysql}"

if [[ -n "$USER_ID" && ! "$USER_ID" =~ ^[0-9]+$ ]]; then
  echo "USER_ID must be numeric: $USER_ID" >&2
  exit 2
fi

sql_string() {
  local value="${1//\\/\\\\}"
  value="${value//\'/\'\'}"
  printf "'%s'" "$value"
}

APP_SQL="$(sql_string "$APP_CODE")"
USER_SQL="$(sql_string "$USER_ID")"
POOL_SQL="$(sql_string "$POOL_ID")"
RESET_SHARED_SQL="$(sql_string "$RESET_SHARED")"

docker exec -i "$MYSQL_CONTAINER" mysql -uroot -proot <<SQL
SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;
USE hyapp_activity;
SET @app_code := ${APP_SQL};
SET @user_id := ${USER_SQL};
SET @pool_id := ${POOL_SQL};
SET @reset_shared := ${RESET_SHARED_SQL};
SET @run_id := REPLACE(UUID(), '-', '');

CREATE TABLE IF NOT EXISTS local_lucky_reset_draws (
  run_id VARCHAR(64) NOT NULL,
  draw_id VARCHAR(128) NOT NULL,
  command_id VARCHAR(128) NOT NULL,
  user_id BIGINT NOT NULL,
  pool_id VARCHAR(96) NOT NULL,
  room_id VARCHAR(96) NOT NULL,
  anchor_id VARCHAR(96) NOT NULL,
  device_id VARCHAR(128) NOT NULL,
  PRIMARY KEY (run_id, draw_id),
  KEY idx_local_lucky_reset_draw_command (run_id, command_id),
  KEY idx_local_lucky_reset_draw_scope (run_id, pool_id, user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS local_lucky_reset_wallet_txs (
  run_id VARCHAR(64) NOT NULL,
  app_code VARCHAR(32) NOT NULL,
  transaction_id VARCHAR(96) NOT NULL,
  PRIMARY KEY (run_id, app_code, transaction_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

DELETE FROM local_lucky_reset_draws WHERE run_id = @run_id;
DELETE FROM local_lucky_reset_wallet_txs WHERE run_id = @run_id;

INSERT INTO local_lucky_reset_draws (run_id, draw_id, command_id, user_id, pool_id, room_id, anchor_id, device_id)
SELECT @run_id, draw_id, command_id, user_id, pool_id, room_id, anchor_id, device_id
FROM hyapp_activity.lucky_draw_records
WHERE app_code = @app_code
  AND (@user_id = '' OR user_id = CAST(NULLIF(@user_id, '') AS UNSIGNED))
  AND (@pool_id = '' OR pool_id = @pool_id);

INSERT IGNORE INTO local_lucky_reset_wallet_txs (run_id, app_code, transaction_id)
SELECT @run_id, wt.app_code, wt.transaction_id
FROM hyapp_wallet.wallet_transactions wt
JOIN local_lucky_reset_draws d
  ON d.run_id = @run_id
 AND wt.app_code = @app_code
 AND wt.biz_type = 'lucky_gift_reward'
 AND wt.command_id = CONCAT('lucky_reward:', d.draw_id);

START TRANSACTION;

UPDATE hyapp_wallet.wallet_accounts a
JOIN (
  SELECT e.app_code, e.user_id, e.asset_type,
         SUM(e.available_delta) AS available_delta,
         SUM(e.frozen_delta) AS frozen_delta
  FROM hyapp_wallet.wallet_entries e
  JOIN local_lucky_reset_wallet_txs t
    ON t.run_id = @run_id AND t.app_code = e.app_code AND t.transaction_id = e.transaction_id
  GROUP BY e.app_code, e.user_id, e.asset_type
) x
  ON x.app_code = a.app_code AND x.user_id = a.user_id AND x.asset_type = a.asset_type
SET a.available_amount = a.available_amount - x.available_delta,
    a.frozen_amount = a.frozen_amount - x.frozen_delta,
    a.version = a.version + 1,
    a.updated_at_ms = UNIX_TIMESTAMP(UTC_TIMESTAMP(3)) * 1000;

DELETE wo
FROM hyapp_wallet.wallet_outbox wo
JOIN local_lucky_reset_wallet_txs t
  ON t.run_id = @run_id AND t.app_code = wo.app_code AND t.transaction_id = wo.transaction_id;

DELETE e
FROM hyapp_wallet.wallet_entries e
JOIN local_lucky_reset_wallet_txs t
  ON t.run_id = @run_id AND t.app_code = e.app_code AND t.transaction_id = e.transaction_id;

DELETE wt
FROM hyapp_wallet.wallet_transactions wt
JOIN local_lucky_reset_wallet_txs t
  ON t.run_id = @run_id AND t.app_code = wt.app_code AND t.transaction_id = wt.transaction_id;

DELETE ao
FROM hyapp_activity.activity_outbox ao
JOIN local_lucky_reset_draws d
  ON d.run_id = @run_id
 AND ao.app_code = @app_code
 AND ao.event_type = 'LuckyGiftDrawn'
 AND CONVERT(ao.payload USING utf8mb4) COLLATE utf8mb4_unicode_ci LIKE CONCAT('%', d.draw_id, '%') COLLATE utf8mb4_unicode_ci;

DELETE dr
FROM hyapp_activity.lucky_draw_records dr
JOIN local_lucky_reset_draws d
  ON d.run_id = @run_id AND d.draw_id = dr.draw_id
WHERE dr.app_code = @app_code;

DELETE FROM hyapp_activity.lucky_user_states
WHERE app_code = @app_code
  AND (@user_id = '' OR user_id = CAST(NULLIF(@user_id, '') AS UNSIGNED))
  AND (@pool_id = '' OR gift_id = @pool_id);

DELETE rc
FROM hyapp_activity.lucky_risk_counters rc
LEFT JOIN (
  SELECT 'user' AS scope_type, CONCAT(pool_id, ':', user_id) AS scope_id FROM local_lucky_reset_draws WHERE run_id = @run_id
  UNION SELECT 'device', CONCAT(pool_id, ':', device_id) FROM local_lucky_reset_draws WHERE run_id = @run_id AND device_id <> ''
  UNION SELECT 'room', CONCAT(pool_id, ':', room_id) FROM local_lucky_reset_draws WHERE run_id = @run_id AND room_id <> ''
  UNION SELECT 'anchor', CONCAT(pool_id, ':', anchor_id) FROM local_lucky_reset_draws WHERE run_id = @run_id AND anchor_id <> ''
) s ON s.scope_type = rc.scope_type AND s.scope_id = rc.scope_id
WHERE rc.app_code = @app_code
  AND (@user_id = '' OR s.scope_id IS NOT NULL)
  AND (@pool_id = '' OR rc.scope_id = @pool_id OR rc.scope_id LIKE CONCAT(@pool_id, ':%'));

DELETE FROM hyapp_activity.lucky_rtp_windows
WHERE @reset_shared = '1'
  AND app_code = @app_code
  AND (@pool_id = '' OR scope_id = @pool_id OR scope_id LIKE CONCAT(@pool_id, ':%'));

DELETE FROM hyapp_activity.lucky_pools
WHERE @reset_shared = '1'
  AND app_code = @app_code
  AND (@pool_id = '' OR scope_id = @pool_id OR scope_id LIKE CONCAT(@pool_id, ':%'));

DELETE FROM hyapp_activity.lucky_room_atmosphere_pools
WHERE @reset_shared = '1'
  AND app_code = @app_code
  AND (@pool_id = '' OR room_id IN (SELECT room_id FROM local_lucky_reset_draws WHERE run_id = @run_id));

DELETE FROM hyapp_activity.lucky_activity_budgets
WHERE @reset_shared = '1'
  AND app_code = @app_code
  AND (@pool_id = '' OR gift_id = @pool_id);

COMMIT;

SELECT JSON_OBJECT(
  'app_code', @app_code,
  'user_id', @user_id,
  'pool_id', @pool_id,
  'reset_shared', @reset_shared,
  'remaining_draw_records', (SELECT COUNT(*) FROM hyapp_activity.lucky_draw_records WHERE app_code = @app_code AND (@user_id = '' OR user_id = CAST(NULLIF(@user_id, '') AS UNSIGNED)) AND (@pool_id = '' OR pool_id = @pool_id)),
  'remaining_user_states', (SELECT COUNT(*) FROM hyapp_activity.lucky_user_states WHERE app_code = @app_code AND (@user_id = '' OR user_id = CAST(NULLIF(@user_id, '') AS UNSIGNED)) AND (@pool_id = '' OR gift_id = @pool_id))
) AS result;

DELETE FROM local_lucky_reset_wallet_txs WHERE run_id = @run_id;
DELETE FROM local_lucky_reset_draws WHERE run_id = @run_id;
SQL
