# Post-Deployment Verification (AGENTS.md v16.0)
# Smoke tests to verify deployment success

param(
    [string]$HostUrl = "http://127.0.0.1:5002",
    [int]$MaxRetries = 5,
    [int]$RetryDelay = 5
)

Write-Host "=== POST-DEPLOYMENT SMOKE TESTS ===" -ForegroundColor Green
Write-Host "Target: $HostUrl" -ForegroundColor Cyan
Write-Host ""

# Wait for Host to start
Write-Host "[1/4] Waiting for Host to start listening..." -ForegroundColor Yellow
$hostReady = $false
for ($i = 0; $i -lt $MaxRetries; $i++) {
    try {
        $response = Invoke-WebRequest -Uri "$HostUrl/health" -Method Get -ErrorAction Stop -TimeoutSec 3
        if ($response.StatusCode -eq 200) {
            Write-Host "✅ Host listening on $HostUrl" -ForegroundColor Green
            $hostReady = $true
            break
        }
    }
    catch {
        Write-Host "  Attempt $($i+1)/$MaxRetries: Waiting..." -ForegroundColor Gray
        Start-Sleep -Seconds $RetryDelay
    }
}

if (-not $hostReady) {
    Write-Host "❌ Host did not start within $($MaxRetries * $RetryDelay)s" -ForegroundColor Red
    exit 1
}

# Health check
Write-Host "[2/4] Verifying health check..." -ForegroundColor Yellow
try {
    $health = Invoke-WebRequest -Uri "$HostUrl/health" -Method Get | ConvertFrom-Json
    Write-Host "✅ Health check passed: $($health.status)" -ForegroundColor Green
}
catch {
    Write-Host "❌ Health check failed: $_" -ForegroundColor Red
    exit 1
}

# Hangfire jobs check
Write-Host "[3/4] Verifying Hangfire jobs..." -ForegroundColor Yellow
try {
    $jobs = Invoke-WebRequest -Uri "$HostUrl/hangfire/api/servers" -Method Get
    if ($jobs.StatusCode -eq 200) {
        Write-Host "✅ Hangfire responding" -ForegroundColor Green
    }
}
catch {
    Write-Host "⚠️  Hangfire API not available (expected in some deployments)" -ForegroundColor Yellow
}

# Database connection check
Write-Host "[4/4] Verifying database..." -ForegroundColor Yellow
try {
    $testConn = New-Object System.Net.Sockets.TcpClient
    $testConn.ConnectAsync("localhost", 5432).Wait(3000)
    $testConn.Close()
    Write-Host "✅ Database reachable" -ForegroundColor Green
}
catch {
    Write-Host "❌ Database not reachable: $_" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "✅ All post-deployment checks passed!" -ForegroundColor Green
exit 0
