# Analyze 404 and 500 errors in detail - categorize root causes
$companyUrl = "http://localhost:8006"

# Login
$loginBody = '{"tenantCode":"T202605253515","username":"admin","password":"admin123"}'
$loginResp = Invoke-WebRequest -Uri "$companyUrl/login" -Method POST -ContentType "application/json" -Body $loginBody -UseBasicParsing
$loginJson = $loginResp.Content | ConvertFrom-Json
$token = $loginJson.token
Write-Host "Token OK"
$headers = @{ Authorization = "Bearer $token" }

# Read the test results
$content = Get-Content "d:\ylrz\saasadminui\api_test_results.txt" -Raw
$sections = $content -split "=== "

# Parse 404 and 500
$notFound = @()
$serverErr = @()
foreach ($section in $sections) {
    if ($section.StartsWith("404 Not Found")) {
        $notFound = ($section -split "`n" | Where-Object { $_.Trim() -ne "" -and $_ -notmatch "^404 Not Found" })
    } elseif ($section.StartsWith("500 Server Error")) {
        $serverErr = ($section -split "`n" | Where-Object { $_.Trim() -ne "" -and $_ -notmatch "^500 Server Error" })
    }
}

# Analyze 404: categorize by issue type
Write-Host "=== 404 Analysis ==="
Write-Host "Total 404s: $($notFound.Count)"

# Category 1: Trailing / paths (e.g. /ad/ vs /ad)
$trailingSlashPaths = $notFound | Where-Object { $_ -match "//\s" -or $_ -match "/\s+\|" }
Write-Host "Trailing slash paths: $($trailingSlashPaths.Count)"

# Category 2: CamelCase entity paths (e.g. /ad/AdDyAccount vs /ad/adDyAccount)
$camelCasePaths = $notFound | Where-Object { $_ -match "/[A-Z][a-z]+[A-Z]" }
Write-Host "CamelCase entity paths: $($camelCasePaths.Count)"

# Category 3: Module paths that might not exist
$modulePaths = @{}
foreach ($line in $notFound) {
    if ($line -match "^\s*/([^/]+)/") {
        $mod = $Matches[1]
        if (-not $modulePaths.ContainsKey($mod)) { $modulePaths[$mod] = 0 }
        $modulePaths[$mod]++
    }
}

# Test some specific 500 errors to understand the error message
Write-Host "`n=== Sample 500 Error Details ==="
$sample500 = $serverErr | Select-Object -First 10
foreach ($line in $sample500) {
    if ($line -match "^\s*(/\S+)") {
        $path = $Matches[1]
        try {
            $resp = Invoke-WebRequest -Uri "$companyUrl$path" -Method GET -Headers $headers -UseBasicParsing -TimeoutSec 5
            $body = $resp.Content | ConvertFrom-Json
            Write-Host "$path => code=$($body.code) msg=$($body.msg)"
        } catch {
            $err = $_.Exception.Message
            if ($err -match "500") {
                # Try to get response body for 500
                try {
                    $errResp = Invoke-WebRequest -Uri "$companyUrl$path" -Method GET -Headers $headers -UseBasicParsing -TimeoutSec 5 -ErrorAction Stop
                    Write-Host "$path => $($errResp.Content.Substring(0, [Math]::Min(200, $errResp.Content.Length)))"
                } catch {
                    Write-Host "$path => HTTP 500 (no response body available)"
                }
            } else {
                Write-Host "$path => $err"
            }
        }
    }
}

# Test some specific 404 errors to understand
Write-Host "`n=== Sample 404 Error Details ==="
# Test /ad module paths (case sensitivity check)
$testCases = @(
    "/ad/AdDyAccount/list",
    "/ad/adDyAccount/list",
    "/ad/ad_dy_account/list",
    "/his/doctor/list",
    "/his/doctor/export",
    "/his/healthRecord/list",
    "/his/healthrecord/list",
    "/company/companyUser/list",
    "/companyUser/list",
    "/store/store/list",
    "/store/storeProduct/list",
    "/course/courseDomainName/list"
)

foreach ($path in $testCases) {
    try {
        $resp = Invoke-WebRequest -Uri "$companyUrl$path" -Method GET -Headers $headers -UseBasicParsing -TimeoutSec 5
        $body = $resp.Content | ConvertFrom-Json
        Write-Host "$path => code=$($body.code) msg=$($body.msg)"
    } catch {
        $err = $_.Exception.Message
        if ($err -match "(\d{3})") {
            Write-Host "$path => HTTP $($Matches[1])"
        } else {
            Write-Host "$path => $err"
        }
    }
}

# Count 404 paths that have a corresponding path with different casing
Write-Host "`n=== Case Sensitivity Check ==="
$lowercasePaths = @{}
foreach ($line in $notFound) {
    if ($line -match "^\s*(/\S+)") {
        $path = $Matches[1]
        $lower = $path.ToLower()
        if (-not $lowercasePaths.ContainsKey($lower)) {
            $lowercasePaths[$lower] = @()
        }
        $lowercasePaths[$lower] += $path
    }
}

$caseConflicts = $lowercasePaths.GetEnumerator() | Where-Object { $_.Value.Count -gt 1 }
Write-Host "Paths with case variants: $($caseConflicts.Count)"
$caseConflicts | Select-Object -First 10 | ForEach-Object {
    Write-Host "  $($_.Key): $($_.Value -join ', ')"
}
