# Aplicar padrão de autenticação híbrida em TODOS os 63 endpoints

Write-Host "=== BULK UPDATE: HYBRID AUTH PATTERN ===" -ForegroundColor Cyan

$functionsPath = "supabase/functions"
$indexFiles = Get-ChildItem -Path $functionsPath -Filter "index.ts" -Recurse

$updated = 0
$skipped = 0
$alreadyDone = 0

foreach ($file in $indexFiles) {
    $relativePath = $file.FullName.Replace((Get-Location).Path + "\", "")
    $functionName = $file.Directory.Name
    
    # Pular _shared
    if ($functionName -eq "_shared") {
        continue
    }
    
    $content = Get-Content $file.FullName -Raw
    
    # Verificar se já foi atualizado
    if ($content -match "validateExternalAuth|x-external-jwt") {
        Write-Host "✓ $functionName - Already updated" -ForegroundColor DarkGray
        $alreadyDone++
        continue
    }
    
    # Verificar se tem autenticação para substituir
    $hasOldAuth = $content -match 'auth\.getUser\(\)|Authorization.*req\.headers'
    
    if (-not $hasOldAuth) {
        Write-Host "⊘ $functionName - No auth found" -ForegroundColor Gray
        $skipped++
        continue
    }
    
    Write-Host "🔄 $functionName - Updating..." -ForegroundColor Yellow
    
    # 1. Adicionar import do helper (após imports do supabase-js)
    if ($content -match 'import.*supabase-js') {
        $content = $content -replace '(import.*from.*supabase-js.*?\n)', "`$1import { validateExternalAuth } from ""../_shared/auth.ts"";`n"
    }
    
    # 2. Substituir padrão de autenticação
    # Padrão antigo 1: const authHeader = req.headers.get("Authorization"); + createClient + auth.getUser()
    $content = $content -replace '(?s)const authHeader = req\.headers\.get\("Authorization"\);?\s*const supabase = createClient\([^)]+\)[^;]*;?\s*const \{ data: \{ user \}[^}]*\} = await supabase\.auth\.getUser\(\);?\s*if \(!user\)[^}]*\{[^}]*\}', @'
const { user, externalSupabase, ownSupabase } = await validateExternalAuth(req);
    const supabase = ownSupabase;
'@
    
    # Padrão antigo 2: apenas createClient + auth.getUser() sem authHeader
    $content = $content -replace '(?s)const supabase = createClient\([^)]+,[^)]+,\s*\{ global: \{ headers: \{ Authorization: authHeader[^}]*\}[^)]*\);?\s*const \{ data: \{ user \}[^}]*\} = await supabase\.auth\.getUser\(\);?\s*if \(!user\)[^}]*\{[^}]*\}', @'
const { user, externalSupabase, ownSupabase } = await validateExternalAuth(req);
    const supabase = ownSupabase;
'@
    
    # Salvar
    Set-Content -Path $file.FullName -Value $content -NoNewline
    $updated++
    Write-Host "✅ $functionName" -ForegroundColor Green
}

Write-Host ""
Write-Host "=== SUMMARY ===" -ForegroundColor Cyan
Write-Host "✅ Updated: $updated" -ForegroundColor Green
Write-Host "✓ Already done: $alreadyDone" -ForegroundColor Gray
Write-Host "⊘ Skipped: $skipped" -ForegroundColor Yellow
Write-Host ""

if ($updated -gt 0) {
    Write-Host "Next step: Deploy all functions" -ForegroundColor Yellow
    Write-Host "Run: pnpx supabase functions deploy" -ForegroundColor Cyan
}
