#!/usr/bin/env bash
# 生产上线：清空全部业务数据，仅保留 admin + WC2026 赛事示例（无代理/玩家/充值/注单）
#
# 与「pnpm db:seed」的区别：
#   db:seed   增量写入，不删已有玩家、充值订单等
#   本脚本   TRUNCATE 全部业务表 + production seed
#
# 用法（项目根目录，Linux 服务器）：
#   chmod +x scripts/prod-init-db.sh
#   CONFIRM=YES ./scripts/prod-init-db.sh
#   CONFIRM=YES ./scripts/prod-init-db.sh --skip-backup
#
# 前置：docker compose -f docker-compose.prod.yml up -d 且 api/postgres 在运行

set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
COMPOSE=(docker compose -f "$ROOT/docker-compose.prod.yml")
ENV_FILE="$ROOT/.env.docker"
SKIP_BACKUP=false

if [ "${CONFIRM:-}" != "YES" ]; then
  echo "错误：将删除全部业务数据（玩家、代理、充值、注单、审计等），仅保留 admin 与 WC2026 赛事示例。"
  echo ""
  echo "若已确认，请执行："
  echo "  CONFIRM=YES $0 [--skip-backup]"
  exit 1
fi

for arg in "$@"; do
  if [ "$arg" = "--skip-backup" ]; then
    SKIP_BACKUP=true
  fi
done

if [ -f "$ENV_FILE" ]; then
  COMPOSE+=(--env-file "$ENV_FILE")
fi

cd "$ROOT"

echo "[prod-init-db] 检查容器…"
"${COMPOSE[@]}" ps --status running api postgres redis >/dev/null 2>&1 || {
  echo "[prod-init-db] 请先启动: docker compose -f docker-compose.prod.yml --env-file .env.docker up -d"
  exit 1
}

if [ "$SKIP_BACKUP" = false ]; then
  BACKUP_DIR="$ROOT/backups"
  mkdir -p "$BACKUP_DIR"
  STAMP="$(date +%Y%m%d-%H%M%S)"
  BACKUP_FILE="$BACKUP_DIR/thebet365-db-prod-init-$STAMP.sql.gz"
  echo "[prod-init-db] 备份 PostgreSQL → $BACKUP_FILE"
  "${COMPOSE[@]}" exec -T postgres pg_dump -U thebet365 -d thebet365 -F p | gzip -c > "$BACKUP_FILE"
  if command -v sha256sum >/dev/null 2>&1; then
    (cd "$BACKUP_DIR" && sha256sum "$(basename "$BACKUP_FILE")" > "$(basename "$BACKUP_FILE").sha256")
  elif command -v shasum >/dev/null 2>&1; then
    (cd "$BACKUP_DIR" && shasum -a 256 "$(basename "$BACKUP_FILE")" > "$(basename "$BACKUP_FILE").sha256")
  else
    echo "[prod-init-db] 警告：未找到 sha256sum 或 shasum，跳过校验文件"
  fi
  echo "[prod-init-db] 备份完成"
else
  echo "[prod-init-db] 已跳过备份 (--skip-backup)"
fi

echo "[prod-init-db] 执行数据库迁移…"
"${COMPOSE[@]}" exec -T api sh -c 'cd /app/apps/api && npx prisma migrate deploy && npx prisma generate'

echo "[prod-init-db] 生产模式初始化（admin + WC2026 赛事）…"
"${COMPOSE[@]}" exec -T \
  -e INIT_DATABASE_CONFIRM=YES \
  -e ALLOW_DB_RESET=true \
  -e SEED_MODE=production \
  -e NODE_ENV=production \
  api \
  node dist/infrastructure/database/reset-and-seed-cli.js --yes --production

echo "[prod-init-db] 清空 Redis…"
"${COMPOSE[@]}" exec -T redis redis-cli FLUSHALL >/dev/null || true

echo ""
echo "[prod-init-db] 完成。"
echo "  管理员: admin / Admin@123（建议登录后立即修改密码）"
echo "  赛事: WC2026 小组赛 72 场 + 48 强优胜盘"
echo ""
echo "后续建议："
echo "  1. .env.docker 中 SEED_DATABASE=false，避免重启 api 重复 seed"
echo "  2. docker compose -f docker-compose.prod.yml --env-file .env.docker restart api"
echo "  3. 勿长期保留 ALLOW_DB_RESET=true"
