# 运行数据库迁移
# 用途: 添加general_conversations和general_messages表

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  执行数据库迁移: 添加通用对话表" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# 读取.env获取数据库连接信息
$envFile = Get-Content .env
$dbUrl = ($envFile | Select-String "DATABASE_URL").ToString().Split('=')[1].Trim()

Write-Host "📦 数据库URL: $($dbUrl.Substring(0, 30))..." -ForegroundColor Yellow
Write-Host ""

# 使用Prisma db push（开发环境最快）
Write-Host "[1/2] 同步数据库Schema..." -ForegroundColor Green
npx prisma db push --skip-generate

if ($LASTEXITCODE -eq 0) {
    Write-Host "✅ Schema同步成功！" -ForegroundColor Green
    Write-Host ""
    
    Write-Host "[2/2] 生成Prisma Client..." -ForegroundColor Green
    npx prisma generate
    
    if ($LASTEXITCODE -eq 0) {
        Write-Host "✅ Prisma Client生成成功！" -ForegroundColor Green
        Write-Host ""
        Write-Host "========================================" -ForegroundColor Cyan
        Write-Host "  ✅ 迁移完成！请重启后端服务" -ForegroundColor Cyan
        Write-Host "========================================" -ForegroundColor Cyan
    } else {
        Write-Host "❌ Prisma Client生成失败" -ForegroundColor Red
    }
} else {
    Write-Host "❌ Schema同步失败，请检查数据库连接" -ForegroundColor Red
    Write-Host ""
    Write-Host "💡 提示：请确保PostgreSQL服务正在运行" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "按任意键退出..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

