# Test Hybrid Architecture (External JWT + Own DB)
# External Supabase = Authentication source of truth
# Own Supabase = Complementary data only

Write-Host "=== HYBRID ARCHITECTURE TEST ===" -ForegroundColor Cyan
Write-Host ""

# 1. Login to External Supabase
Write-Host "[1/4] Logging into External Supabase..." -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 Token obtained: $($jwtToken.Substring(0,40))..." -ForegroundColor Green
    Write-Host ""
} catch {
    Write-Host "❌ Login failed: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

# 2. Get a Doctor ID from External Supabase
Write-Host "[2/4] Fetching doctor from External Supabase..." -ForegroundColor Yellow
$extHeaders = @{
    "apikey" = $externalApiKey
    "Authorization" = "Bearer $jwtToken"
}

try {
    $doctors = Invoke-RestMethod `
        -Uri "https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/doctors?select=id,full_name&limit=1" `
        -Headers $extHeaders
    
    $doctorId = $doctors[0].id
    $doctorName = $doctors[0].full_name
    Write-Host "✅ Doctor: $doctorName (ID: $doctorId)" -ForegroundColor Green
    Write-Host ""
} catch {
    Write-Host "❌ Failed to fetch doctor: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

# 3. Deploy doctor-summary function
Write-Host "[3/4] Deploying doctor-summary function..." -ForegroundColor Yellow
try {
    $deployOutput = pnpx supabase functions deploy doctor-summary 2>&1
    Write-Host "✅ Function deployed" -ForegroundColor Green
    Write-Host ""
    Start-Sleep -Seconds 3
} catch {
    Write-Host "⚠️ Deploy warning (continuing...)" -ForegroundColor Yellow
    Write-Host ""
}

# 4. Test doctor-summary endpoint (External JWT + Own DB)
Write-Host "[4/4] Testing doctor-summary endpoint..." -ForegroundColor Yellow
Write-Host "      External JWT: $($jwtToken.Substring(0,30))..." -ForegroundColor Gray
Write-Host "      Own Endpoint: https://etblfypcxxtvvuqjkrgd.supabase.co/functions/v1/doctor-summary" -ForegroundColor Gray
Write-Host ""

$testBody = @{
    doctor_id = $doctorId
} | ConvertTo-Json

# Use SERVICE_ROLE key in Authorization (bypass Edge Runtime JWT validation)
# External JWT passed in custom header for validation inside function
$ownServiceKey = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImV0YmxmeXBjeHh0dnZ1cWprcmdkIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc2NDE1NzM2MywiZXhwIjoyMDc5NzMzMzYzfQ.dJVEzm26MuxIEAzeeIOLd-83fFHhfX0Z7UgF4LEX-98"

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

try {
    $result = Invoke-RestMethod `
        -Uri "https://etblfypcxxtvvuqjkrgd.supabase.co/functions/v1/doctor-summary" `
        -Method Post `
        -Body $testBody `
        -Headers $testHeaders
    
    Write-Host "✅ SUCCESS! Hybrid architecture working!" -ForegroundColor Green
    Write-Host ""
    Write-Host "=== RESULT ===" -ForegroundColor Cyan
    $result | ConvertTo-Json -Depth 4
    Write-Host ""
    
} catch {
    Write-Host "❌ Test failed: $($_.Exception.Message)" -ForegroundColor Red
    
    # Try to get detailed error
    try {
        $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
        $errorBody = $reader.ReadToEnd()
        Write-Host "Error details: $errorBody" -ForegroundColor Red
    } catch {
        # Ignore
    }
    
    exit 1
}

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