$ErrorActionPreference = 'Stop'

Set-Location -LiteralPath $PSScriptRoot

$phpCommand = Get-Command php.exe -ErrorAction SilentlyContinue
$php = if ($phpCommand) {
    $phpCommand.Source
} else {
    Get-ChildItem -Path "$env:LOCALAPPDATA\Microsoft\WinGet\Packages\PHP.PHP.*" -Filter php.exe -Recurse -ErrorAction SilentlyContinue |
        Sort-Object FullName -Descending |
        Select-Object -First 1 -ExpandProperty FullName
}

if (-not $php) {
    throw 'PHP was not found. Install PHP 8.2+ and reopen PowerShell.'
}

if (-not (Test-Path -LiteralPath 'vendor\autoload.php')) {
    throw 'Laravel dependencies are missing. Run composer install before previewing.'
}

if (-not (Test-Path -LiteralPath 'database\database.sqlite')) {
    New-Item -ItemType File -Path 'database\database.sqlite' | Out-Null
}

try {
    $preview = Invoke-WebRequest -Uri 'http://127.0.0.1:8000/' -UseBasicParsing -TimeoutSec 2
} catch {
    $preview = $null
}

if ($preview -and $preview.StatusCode -ge 200 -and $preview.StatusCode -lt 500) {
    Write-Host 'A preview is already listening at http://127.0.0.1:8000' -ForegroundColor Green
    exit 0
}

Write-Host 'Starting MGG preview at http://127.0.0.1:8000' -ForegroundColor Cyan
Write-Host 'Press Ctrl+C to stop the preview server.' -ForegroundColor Yellow
& $php artisan serve --host=127.0.0.1 --port=8000
