# Compare auth vs no-auth on fs-admin
$loginBody = @{
    tenantCode = "T202605253515"
    username = "admin"
    password = "admin123"
} | ConvertTo-Json

$resp = Invoke-RestMethod -Uri "http://localhost:8006/login" -Method POST -ContentType "application/json" -Body $loginBody
$token = $resp.token

Write-Output "=== NO AUTH ==="
try {
    $r = Invoke-WebRequest -Uri "http://localhost:8003/his/healthTongue/list" -Method GET -UseBasicParsing -ErrorAction Stop
    $body = $r.Content | ConvertFrom-Json
    Write-Output "  HTTP $($r.StatusCode) code=$($body.code) msg=$($body.msg)"
} catch {
    Write-Output "  HTTP $($_.Exception.Response.StatusCode.value__)"
}

Write-Output ""
Write-Output "=== WITH AUTH (fs-company token) ==="
try {
    $headers = @{ Authorization = "Bearer $token" }
    $r = Invoke-WebRequest -Uri "http://localhost:8003/his/healthTongue/list" -Method GET -Headers $headers -UseBasicParsing -ErrorAction Stop
    $body = $r.Content | ConvertFrom-Json
    Write-Output "  HTTP $($r.StatusCode) code=$($body.code) msg=$($body.msg)"
} catch {
    $status = $_.Exception.Response.StatusCode.value__
    Write-Output "  HTTP $status"
    if ($_.Exception.Response) {
        $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
        $reader.BaseStream.Position = 0
        $respBody = $reader.ReadToEnd()
        Write-Output "  Body: $($respBody.Substring(0, [Math]::Min(200, $respBody.Length)))"
    }
}

Write-Output ""
Write-Output "=== Login on fs-admin directly ==="
$adminLoginBody = @{
    username = "admin"
    password = "admin123"
} | ConvertTo-Json
try {
    $adminResp = Invoke-RestMethod -Uri "http://localhost:8003/login" -Method POST -ContentType "application/json" -Body $adminLoginBody
    Write-Output "  Login code=$($adminResp.code) msg=$($adminResp.msg)"
    if ($adminResp.token) {
        $adminToken = $adminResp.token
        Write-Output "  Admin token obtained!"
        
        Write-Output ""
        Write-Output "=== WITH fs-admin TOKEN ==="
        $adminHeaders = @{ Authorization = "Bearer $adminToken" }
        try {
            $r2 = Invoke-WebRequest -Uri "http://localhost:8003/his/healthTongue/list" -Method GET -Headers $adminHeaders -UseBasicParsing -ErrorAction Stop
            $body2 = $r2.Content | ConvertFrom-Json
            Write-Output "  HTTP $($r2.StatusCode) code=$($body2.code) msg=$($body2.msg)"
        } catch {
            Write-Output "  HTTP $($_.Exception.Response.StatusCode.value__)"
        }
    }
} catch {
    Write-Output "  Login error: $($_.Exception.Message)"
}
