$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: $($token.Substring(0,20))..."

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

# Test some specific his endpoints that SHOULD be loaded from fs-admin-saas
$tests = @(
    '/his/doctor/list',       # fs-company own controller -> should be 200
    '/his/follow/list',       # EXCLUDED in excludeFilters -> should be 404, but company has /his/follow too
    '/his/store/list',        # from fs-admin-saas, NOT excluded
    '/his/user/list',         # from fs-admin-saas, NOT excluded
    '/his/storeOrder/list',   # from fs-admin-saas, NOT excluded
    '/course/courseDomainName/list',  # from fs-admin-saas, NOT excluded
    '/course/userCourseComment/list', # from fs-admin-saas, NOT excluded
    '/crm/customer/list',     # EXCLUDED com.fs.crm.controller.*
    '/live/coupon/list',      # EXCLUDED com.fs.live.controller.* BUT live/coupon returned 200 before!
    '/fastGpt/fastGptChatMsg/list',   # EXCLUDED com.fs.fastGpt.*
    '/qw/externalContact/list',       # EXCLUDED com.fs.qw.controller.* BUT working!
    '/qw/tag/list',                   # fs-company own /qw/tag
    '/company/company/list',          # fs-company own
    '/company/companyConfig/list',    # fs-company own
    '/company/easyCall/list',         # fs-company own
    '/system/user/list',              # from fs-admin-saas, routed to 8003
    '/system/dept/list'               # from fs-admin-saas, routed to 8003
)

Write-Output "=== Testing on fs-company (8006) ==="
foreach ($url in $tests) {
    try {
        $r = Invoke-WebRequest -Uri "http://localhost:8006$url" -Method POST -Headers $headers -Body '{}' -UseBasicParsing -TimeoutSec 5
        $body = $r.Content.Substring(0, [Math]::Min(100, $r.Content.Length))
        Write-Output "200 | $url | $body"
    } catch {
        $err = $_.Exception.Message
        if ($err -match '(\d{3})') { $code = $Matches[1] } else { $code = 'ERR' }
        Write-Output "$code | $url"
    }
}

Write-Output ""
Write-Output "=== Testing on fs-admin (8003) ==="
foreach ($url in $tests) {
    try {
        $r = Invoke-WebRequest -Uri "http://localhost:8003$url" -Method POST -Headers $headers -Body '{}' -UseBasicParsing -TimeoutSec 5
        Write-Output "200 | $url"
    } catch {
        $err = $_.Exception.Message
        if ($err -match '(\d{3})') { $code = $Matches[1] } else { $code = 'ERR' }
        Write-Output "$code | $url"
    }
}
