Param(
    [string]$BaseUrl = "http://localhost:5116",
    [string]$AdminKey = $env:ADMIN_PASSWORD
)

if (-not $AdminKey) {
    Write-Error "Set ADMIN_PASSWORD env var or pass -AdminKey."
    exit 1
}

$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession

function Invoke-Json {
    param(
        [Parameter(Mandatory=$true)][string]$Method,
        [Parameter(Mandatory=$true)][string]$Path,
        [object]$Body = $null,
        [hashtable]$Headers = @{}
    )
    $uri = "$BaseUrl$Path"
    $params = @{
        Method = $Method
        Uri    = $uri
        WebSession = $session
        Headers = $Headers
    }
    if ($Body) { $params.Body = ($Body | ConvertTo-Json -Depth 5); $params.ContentType = "application/json" }
    try {
        $response = Invoke-WebRequest @params -ErrorAction Stop
        if ($response.Content) { return ($response.Content | ConvertFrom-Json) }
        return $null
    } catch {
        Write-Error "Request failed: $Method $uri`n$($_.Exception.Message)"
        if ($_.Exception.Response -and $_.Exception.Response.GetResponseStream()) {
            $reader = New-Object IO.StreamReader $_.Exception.Response.GetResponseStream()
            Write-Error "Response body:`n$($reader.ReadToEnd())"
        }
        exit 1
    }
}

Write-Host "Health check..."
Invoke-Json -Method GET -Path "/health" | Out-Host

Write-Host "`nAdmin factory reset (clears players, suggestions, votes)..."
Invoke-Json -Method POST -Path "/api/admin/factory-reset" -Headers @{ "X-Admin-Key" = $AdminKey } | Out-Host

# TODO

Write-Host "`nAdmin factory reset (clears players, suggestions, votes)..."
Invoke-Json -Method POST -Path "/api/admin/factory-reset" -Headers @{ "X-Admin-Key" = $AdminKey } | Out-Host

Write-Host "`nSmoke test completed."
