# Test ANY endpoint with hybrid auth
param(
    [Parameter(Mandatory=$true)]
    [string]$EndpointName,
    
    [Parameter(Mandatory=$false)]
    [hashtable]$Body = @{}
)

Write-Host "=== HYBRID AUTH TEST: $EndpointName ===" -ForegroundColor Cyan

# 1. Login to External Supabase
Write-Host "[1/3] Authenticating..." -ForegroundColor Yellow
$loginBody = '{"email":"riseup@popcode.com.br","password":"riseup"}'
$externalApiKey = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ"

try {
    $loginResponse = Invoke-RestMethod `
        -Uri "https://yuanqfswhberkoevtmfr.supabase.co/auth/v1/token?grant_type=password" `
        -Method Post `
        -Body $loginBody `
        -ContentType "application/json" `
        -Headers @{"apikey"=$externalApiKey}
    
    $jwtToken = $loginResponse.access_token
    Write-Host "✅ JWT obtained" -ForegroundColor Green
} catch {
    Write-Host "❌ Login failed: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

# 2. Call endpoint
Write-Host "[2/3] Calling $EndpointName..." -ForegroundColor Yellow

$ownServiceKey = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImV0YmxmeXBjeHh0dnZ1cWprcmdkIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc2NDE1NzM2MywiZXhwIjoyMDc5NzMzMzYzfQ.dJVEzm26MuxIEAzeeIOLd-83fFHhfX0Z7UgF4LEX-98"

$testBody = $Body | ConvertTo-Json -Compress
if ($testBody -eq "{}") { $testBody = "{}" }

$headers = @{
    "Authorization" = "Bearer $ownServiceKey"
    "x-external-jwt" = $jwtToken
    "apikey" = $ownServiceKey
    "Content-Type" = "application/json"
}

try {
    $result = Invoke-RestMethod `
        -Uri "https://etblfypcxxtvvuqjkrgd.supabase.co/functions/v1/$EndpointName" `
        -Method Post `
        -Body $testBody `
        -Headers $headers
    
    Write-Host "✅ SUCCESS!" -ForegroundColor Green
    Write-Host ""
    Write-Host "=== RESPONSE ===" -ForegroundColor Cyan
    $result | ConvertTo-Json -Depth 5
    Write-Host ""
    
} catch {
    Write-Host "❌ FAILED: $($_.Exception.Message)" -ForegroundColor Red
    
    try {
        $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
        $errorBody = $reader.ReadToEnd()
        Write-Host "Error details: $errorBody" -ForegroundColor Red
    } catch {}
    
    exit 1
}

Write-Host "=== TEST COMPLETE ===" -ForegroundColor Green
