# Test login directly on backend
$body = '{"tenantCode":"T202605253515","username":"admin","password":"admin123"}'

Write-Host "=== Test 1: Direct backend login (8006) ==="
try {
    $r = Invoke-WebRequest -Uri 'http://localhost:8006/company/login' -Method Post -ContentType 'application/json' -Body $body -UseBasicParsing
    Write-Host "Status: $($r.StatusCode)"
    $json = $r.Content | ConvertFrom-Json
    Write-Host "Code: $($json.code), Msg: $($json.msg)"
    if ($json.token) { Write-Host "Token length: $($json.token.Length)" }
} catch {
    Write-Host "Error: $($_.Exception.Message)"
}

Write-Host "`n=== Test 2: Admin backend login (8003) ==="
try {
    $r = Invoke-WebRequest -Uri 'http://localhost:8003/login' -Method Post -ContentType 'application/json' -Body '{"username":"admin","password":"admin123"}' -UseBasicParsing
    Write-Host "Status: $($r.StatusCode)"
    $json = $r.Content | ConvertFrom-Json
    Write-Host "Code: $($json.code), Msg: $($json.msg)"
} catch {
    Write-Host "Error: $($_.Exception.Message)"
}

Write-Host "`n=== Test 3: Check SecurityConfig anonymous paths ==="
# Check if /company/login is allowed without auth
try {
    $r = Invoke-WebRequest -Uri 'http://localhost:8006/company/login' -Method Post -ContentType 'application/json' -Body $body -UseBasicParsing
    $json = $r.Content | ConvertFrom-Json
    if ($json.code -eq 401) {
        Write-Host "LOGIN PATH NOT IN ANONYMOUS LIST - SecurityConfig issue!"
        Write-Host "The /company/login path needs to be added to anonymous() in SecurityConfig"
    } else {
        Write-Host "Login works, code=$($json.code)"
    }
} catch {
    Write-Host "Request failed entirely"
}
