$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 all backend mappings (deduplicated)
$backendPaths = Get-Content 'd:\ylrz\saasadminui\backend_mappings.txt' | Where-Object { $_ -match '^/' } | Sort-Object -Unique
$backendSet = @{}
foreach ($p in $backendPaths) { $backendSet[$p] = $true }

# Read all 404 errors from previous test
$errFile = 'd:\ylrz\saasadminui\api_errors_final.txt'
$errLines = Get-Content $errFile | Where-Object { $_ -match '^404\|' }

# Parse and deduplicate the 404 URLs
$notFoundUrls = @{}
foreach ($line in $errLines) {
    $parts = $line -split '\|'
    $url = $parts[1]
    if ($url -and -not $notFoundUrls.ContainsKey($url)) {
        $notFoundUrls[$url] = $true
    }
}

Write-Output "Total 404 URLs: $($notFoundUrls.Count)"
Write-Output "Total backend paths: $($backendSet.Count)"

# Test each 404 URL directly against backend (8006) with POST
$results = @{
    directOk = [System.Collections.ArrayList]::new()
    direct404 = [System.Collections.ArrayList]::new()
    direct500 = [System.Collections.ArrayList]::new()
    directErr = [System.Collections.ArrayList]::new()
}

$i = 0
$total = $notFoundUrls.Count

foreach ($url in ($notFoundUrls.Keys | Sort-Object)) {
    $i++
    if ($i % 50 -eq 0) {
        Write-Output "Progress: $i/$total (OK=$($results.directOk.Count) 404=$($results.direct404.Count) 500=$($results.direct500.Count) ERR=$($results.directErr.Count))"
    }
    
    $fullUrl = "http://localhost:8006$url"
    try {
        $r = Invoke-WebRequest -Uri $fullUrl -Method POST -Headers $headers -Body '{}' -UseBasicParsing -TimeoutSec 5
        [void]$results.directOk.Add("OK|$url")
    }
    catch {
        $errMsg = $_.Exception.Message
        if ($errMsg -match '404') {
            [void]$results.direct404.Add("404|$url")
        }
        elseif ($errMsg -match '500') {
            [void]$results.direct500.Add("500|$url")
        }
        elseif ($errMsg -match '401') {
            [void]$results.directOk.Add("401|$url")
        }
        else {
            [void]$results.directErr.Add("ERR|$url|$errMsg")
        }
    }
}

Write-Output ""
Write-Output "=== 404 URLs TESTED DIRECTLY AGAINST BACKEND (8006) ==="
Write-Output "OK (backend has it, proxy is wrong): $($results.directOk.Count)"
Write-Output "404 (backend doesn't have it either): $($results.direct404.Count)"
Write-Output "500 (backend error): $($results.direct500.Count)"
Write-Output "ERR (timeout/other): $($results.directErr.Count)"

# Save results
$output = @()
$output += "=== 404 URLs TESTED DIRECTLY AGAINST BACKEND (8006) ==="
$output += "OK (proxy problem): $($results.directOk.Count)"
$output += "404 (backend missing): $($results.direct404.Count)"
$output += "500 (backend error): $($results.direct500.Count)"
$output += "ERR (timeout): $($results.directErr.Count)"
$output += ""
$output += "=== OK - BACKEND WORKS, PROXY NEEDS FIX ==="
$output += $results.directOk | Sort-Object
$output += ""
$output += "=== 404 - BACKEND DOES NOT HAVE THIS PATH ==="
$output += $results.direct404 | Sort-Object
$output += ""
$output += "=== 500 - BACKEND ERROR ==="
$output += $results.direct500 | Sort-Object
$output += ""
$output += "=== ERR - TIMEOUT/OTHER ==="
$output += $results.directErr | Sort-Object

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