# run_app_and_import.ps1
# This script starts the .NET Aspire AppHost and automatically runs the database import once the WebAPI is ready.

Write-Host "Starting GerbilManager AppHost (this will boot PostgreSQL and the WebAPI)..." -ForegroundColor Cyan

# Start AppHost in the background
$appProcess = Start-Process dotnet -ArgumentList "run --project GerbilManager.AppHost" -PassThru -NoNewWindow

# Function to cleanup process on exit
function Cleanup {
    Write-Host "`nStopping AppHost..." -ForegroundColor Yellow
    if ($appProcess -and -not $appProcess.HasExited) {
        Stop-Process -Id $appProcess.Id -Force
    }
}
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { Cleanup }

try {
    # Poll the import endpoint until it becomes responsive (max 60 seconds)
    $url = "http://localhost:5179/import/ingest-resolved"
    $success = $false
    Write-Host "Waiting for WebAPI to become responsive at $url..." -ForegroundColor Cyan

    for ($i = 0; $i -lt 30; $i++) {
        try {
            # Send a test request or check port
            $response = Invoke-WebRequest -Uri "http://localhost:5179/openapi/v1.json" -Method Get -TimeoutSec 2 -ErrorAction Stop
            if ($response.StatusCode -eq 200) {
                $success = $true
                break
            }
        }
        catch {
            # WebAPI not ready yet
            Start-Sleep -Seconds 2
        }
    }

    if (-not $success) {
        Write-Host "Error: WebAPI did not become ready within 60 seconds." -ForegroundColor Red
        Cleanup
        exit 1
    }

    Write-Host "WebAPI is up! Triggering the database import..." -ForegroundColor Green
    
    # Run the import POST request
    try {
        $importResponse = Invoke-RestMethod -Uri $url -Method Post -ContentType "application/json"
        Write-Host "Import Result: $importResponse" -ForegroundColor Green
        Write-Host "`nThe application is now fully running and imported!" -ForegroundColor Cyan
        Write-Host "Press Ctrl+C in this terminal to stop the application." -ForegroundColor Yellow
        
        # Keep script running to keep the app process alive
        while ($true) {
            Start-Sleep -Seconds 1
        }
    }
    catch {
        Write-Host "Error during database import: $_" -ForegroundColor Red
    }
}
finally {
    Cleanup
}
