# Rollback Procedure (AGENTS.md v16.0 - Safety & Reliability)
# Safely rollback to previous version

param(
    [string]$BackupFile = "D:\JobRoomz\KArtSell.Aegis\backups\kartsell.backup.latest",
    [switch]$Confirm = $false
)

Write-Host "=== ROLLBACK PROCEDURE ===" -ForegroundColor Yellow
Write-Host "WARNING: This will stop the Host and restore the previous version." -ForegroundColor Red
Write-Host ""

if (-not $Confirm) {
    $response = Read-Host "Continue? (yes/no)"
    if ($response -ne "yes") {
        Write-Host "Rollback cancelled." -ForegroundColor Yellow
        exit 0
    }
}

# Step 1: Stop Host
Write-Host "[1/4] Stopping Host..." -ForegroundColor Yellow
try {
    Get-Process | Where-Object { $_.Name -like "*dotnet*" } | Stop-Process -Force
    Start-Sleep -Seconds 5
    Write-Host "✅ Host stopped" -ForegroundColor Green
}
catch {
    Write-Host "⚠️  Host stop warning: $_" -ForegroundColor Yellow
}

# Step 2: Restore database (manual for safety)
Write-Host "[2/4] Database restore required (MANUAL)" -ForegroundColor Yellow
Write-Host "  Run: psql -U kartsell -d kartsell < $BackupFile" -ForegroundColor Cyan

# Step 3: Deploy previous version
Write-Host "[3/4] Deploy previous version binaries..." -ForegroundColor Yellow
Write-Host "  Copy previous release files to src/KArtSell.Host/bin/Release/" -ForegroundColor Cyan

# Step 4: Restart Host
Write-Host "[4/4] Restarting Host..." -ForegroundColor Yellow
try {
    $env:ASPNETCORE_ENVIRONMENT = "Production"
    Start-Process -FilePath "dotnet" -ArgumentList "run --project src/KArtSell.Host --configuration Release"
    Start-Sleep -Seconds 10
    Write-Host "✅ Host restarted" -ForegroundColor Green
}
catch {
    Write-Host "❌ Host restart failed: $_" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "✅ Rollback complete. Verify health check and logs." -ForegroundColor Green
exit 0
