$ErrorActionPreference = "SilentlyContinue"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

# Login
$body = '{"username":"admin","password":"admin123","tenantCode":"T202605253515"}'
$resp = Invoke-WebRequest -Uri 'http://localhost:8006/login' -Method POST -ContentType 'application/json' -Body $body -UseBasicParsing -TimeoutSec 10
$json = $resp.Content | ConvertFrom-Json
$token = $json.token
Write-Output "Token obtained"

$headers = @{ 'Authorization' = "Bearer $token"; 'Content-Type' = 'application/json' }

# Read backend mappings (deduplicated)
$backendPaths = Get-Content 'd:\ylrz\saasadminui\backend_mappings.txt' | Where-Object { $_ -match '^/[a-z]' } | Sort-Object -Unique

Write-Output "Total backend paths to test: $($backendPaths.Count)"

# Test each backend path with /list appended (most common endpoint)
$results = @{
    ok = [System.Collections.ArrayList]::new()
    notFound = [System.Collections.ArrayList]::new()
    serverError = [System.Collections.ArrayList]::new()
    forbidden = [System.Collections.ArrayList]::new()
    err = [System.Collections.ArrayList]::new()
}

$i = 0
$total = $backendPaths.Count

foreach ($path in $backendPaths) {
    $i++
    # Skip paths with {variable}
    if ($path -match '\{') { continue }
    
    # Test /list endpoint
    $testUrl = "http://localhost:8006${path}/list"
    
    if ($i % 50 -eq 0) {
        Write-Output "Progress: $i/$total (OK=$($results.ok.Count) 404=$($results.notFound.Count) 500=$($results.serverError.Count))"
    }
    
    try {
        $r = Invoke-WebRequest -Uri $testUrl -Method POST -Headers $headers -Body '{}' -UseBasicParsing -TimeoutSec 5
        [void]$results.ok.Add("200|$path")
    }
    catch {
        $errMsg = $_.Exception.Message
        if ($errMsg -match '404') {
            [void]$results.notFound.Add("404|$path")
        }
        elseif ($errMsg -match '500') {
            [void]$results.serverError.Add("500|$path")
        }
        elseif ($errMsg -match '403|401') {
            [void]$results.forbidden.Add("403|$path")
        }
        else {
            [void]$results.err.Add("ERR|$path")
        }
    }
}

Write-Output ""
Write-Output "=== BACKEND PATHS TESTED WITH /list ==="
Write-Output "OK: $($results.ok.Count)"
Write-Output "404: $($results.notFound.Count)"
Write-Output "500: $($results.serverError.Count)"
Write-Output "403/401: $($results.forbidden.Count)"
Write-Output "ERR: $($results.err.Count)"

# Save all results grouped by first segment
$output = @()
$output += "=== BACKEND PATH TEST SUMMARY ==="
$output += "OK: $($results.ok.Count)"
$output += "404: $($results.notFound.Count)"
$output += "500: $($results.serverError.Count)"
$output += "403: $($results.forbidden.Count)"
$output += "ERR: $($results.err.Count)"
$output += ""
$output += "=== 200 OK PATHS ==="
$output += $results.ok | Sort-Object
$output += ""
$output += "=== 404 PATHS (backend doesn't have /list) ==="
$output += $results.notFound | Sort-Object
$output += ""
$output += "=== 500 PATHS (backend error) ==="
$output += $results.serverError | Sort-Object
$output += ""
$output += "=== 403/401 PATHS ==="
$output += $results.forbidden | Sort-Object

$output | Out-File -FilePath 'd:\ylrz\saasadminui\backend_path_test.txt' -Encoding utf8
Write-Output "Saved to backend_path_test.txt"
