# 生产上线：清空全部业务数据，仅保留 admin + WC2026 赛事示例
#
# 用法（PowerShell，项目根目录）：
#   $env:CONFIRM = "YES"; .\scripts\prod-init-db.ps1
#   $env:CONFIRM = "YES"; .\scripts\prod-init-db.ps1 -SkipBackup

param(
  [switch]$SkipBackup
)

$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$ComposeFile = Join-Path $Root "docker-compose.prod.yml"
$EnvFile = Join-Path $Root ".env.docker"

if ($env:CONFIRM -ne "YES") {
  Write-Host "错误：将删除全部业务数据，仅保留 admin 与 WC2026 赛事示例。"
  Write-Host ""
  Write-Host '确认后执行: $env:CONFIRM = "YES"; .\scripts\prod-init-db.ps1'
  exit 1
}

$composeArgs = @("-f", $ComposeFile)
if (Test-Path $EnvFile) {
  $composeArgs += @("--env-file", $EnvFile)
}

Set-Location $Root

Write-Host "[prod-init-db] 检查容器…"
docker compose @composeArgs ps --status running api postgres 2>$null | Out-Null
if ($LASTEXITCODE -ne 0) {
  Write-Host "[prod-init-db] 请先启动 docker compose 栈"
  exit 1
}

if (-not $SkipBackup) {
  $backupDir = Join-Path $Root "backups"
  New-Item -ItemType Directory -Force -Path $backupDir | Out-Null
  $stamp = Get-Date -Format "yyyyMMdd-HHmmss"
  $tempFile = Join-Path $backupDir "thebet365-db-prod-init-$stamp.sql"
  $backupFile = "$tempFile.gz"
  Write-Host "[prod-init-db] 备份 → $backupFile"
  docker compose @composeArgs exec -T postgres pg_dump -U thebet365 -d thebet365 -F p | Set-Content -Encoding utf8 $tempFile

  $inputStream = [System.IO.File]::OpenRead($tempFile)
  $outputStream = [System.IO.File]::Create($backupFile)
  try {
    $gzipStream = [System.IO.Compression.GzipStream]::new($outputStream, [System.IO.Compression.CompressionMode]::Compress)
    try {
      $inputStream.CopyTo($gzipStream)
    } finally {
      $gzipStream.Dispose()
    }
  } finally {
    $inputStream.Dispose()
    $outputStream.Dispose()
  }
  Remove-Item $tempFile -Force

  $hash = (Get-FileHash -Algorithm SHA256 $backupFile).Hash.ToLowerInvariant()
  "$hash  $(Split-Path -Leaf $backupFile)" | Set-Content -Encoding UTF8 "$backupFile.sha256"
} else {
  Write-Host "[prod-init-db] 已跳过备份"
}

Write-Host "[prod-init-db] 迁移…"
docker compose @composeArgs exec -T api sh -c "cd /app/apps/api && npx prisma migrate deploy && npx prisma generate"

Write-Host "[prod-init-db] 生产模式初始化…"
docker compose @composeArgs 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

Write-Host "[prod-init-db] 清空 Redis…"
docker compose @composeArgs exec -T redis redis-cli FLUSHALL 2>$null | Out-Null

Write-Host ""
Write-Host "[prod-init-db] 完成。管理员 admin / Admin@123，含 WC2026 赛事示例。"
Write-Host "请将 .env.docker 中 SEED_DATABASE 设为 false 后 restart api"
