# Script para aplicar padrão de autenticação híbrida em TODOS os endpoints
# 
# PADRÃO:
# 1. Import validateExternalAuth from _shared/auth.ts
# 2. Trocar validação de JWT local por validateExternalAuth()
# 3. Usar externalSupabase e ownSupabase do resultado

Write-Host "=== UPDATING ALL ENDPOINTS TO HYBRID AUTH ===" -ForegroundColor Cyan
Write-Host ""

$endpoints = @(
    "user-info",
    "user-update-preferences",
    "availability-create",
    "availability-update",
    "availability-delete",
    "availability-list",
    "availability-slots",
    "exceptions-create",
    "exceptions-delete",
    "exceptions-list",
    "appointments-create",
    "appointments-update",
    "appointments-cancel",
    "waitlist-match",
    "waitlist-remove",
    "virtual-queue-checkin",
    "notifications-subscription",
    "analytics-heatmap",
    "analytics-demand-curve",
    "analytics-ranking-reasons",
    "analytics-monthly-no-show",
    "analytics-specialty-heatmap",
    "analytics-custom-report",
    "reports-list-extended",
    "reports-export-csv",
    "reports-integrity-check",
    "reports-export",
    "doctor-occupancy",
    "doctor-delay-suggestion",
    "patients-history",
    "patients-preferences",
    "patients-update-preferences",
    "patients-portal",
    "accessibility-preferences",
    "accessibility-update-preferences",
    "audit-list",
    "system-health-check",
    "system-cache-rebuild",
    "system-cron-runner",
    "appointments-list",
    "appointments-stats",
    "waitlist-add",
    "waitlist-list",
    "virtual-queue-status",
    "virtual-queue-call-next",
    "notifications-send",
    "notifications-mark-read",
    "notifications-preferences",
    "analytics-overview",
    "analytics-no-show-prediction",
    "teleconsult-start",
    "teleconsult-end",
    "teleconsult-status",
    "gamification-points",
    "gamification-badges",
    "gamification-leaderboard",
    "privacy-consent",
    "privacy-data-export",
    "privacy-data-delete",
    "flags-list",
    "flags-toggle",
    "offline-sync"
)

$updated = 0
$failed = 0

foreach ($endpoint in $endpoints) {
    $path = "supabase/functions/$endpoint/index.ts"
    
    if (-not (Test-Path $path)) {
        Write-Host "⚠️  $endpoint - File not found" -ForegroundColor Yellow
        $failed++
        continue
    }
    
    # Ler conteúdo atual
    $content = Get-Content $path -Raw
    
    # Verificar se já tem validateExternalAuth
    if ($content -match "validateExternalAuth") {
        Write-Host "✓  $endpoint - Already updated" -ForegroundColor Gray
        continue
    }
    
    # Verificar se tem auth.getUser() pattern que precisa ser substituído
    if ($content -notmatch "auth\.getUser\(\)") {
        Write-Host "⊘  $endpoint - No auth pattern found" -ForegroundColor DarkGray
        continue
    }
    
    Write-Host "🔄 $endpoint - Updating..." -ForegroundColor Yellow
    
    # Adicionar import se não existir
    if ($content -notmatch "validateExternalAuth") {
        $content = $content -replace '(import.*from.*supabase-js.*\n)', "`$1import { validateExternalAuth, createAuthErrorResponse } from ""../_shared/auth.ts"";`n"
    }
    
    # Substituir padrão de autenticação
    # Pattern: const { data: { user } } = await supabase.auth.getUser();
    $oldPattern = '(?s)(const authHeader = req\.headers\.get\("Authorization"\);.*?)(const \{ data: \{ user \} \} = await supabase\.auth\.getUser\(\);.*?if \(!user\).*?\n)'
    
    $newPattern = 'const { user, externalSupabase, ownSupabase } = await validateExternalAuth(req);
    const supabase = ownSupabase; // For backward compatibility
'
    
    if ($content -match $oldPattern) {
        $content = $content -replace $oldPattern, $newPattern
        
        # Salvar
        Set-Content -Path $path -Value $content -NoNewline
        Write-Host "✅ $endpoint - Updated!" -ForegroundColor Green
        $updated++
    } else {
        Write-Host "⚠️  $endpoint - Pattern not matched" -ForegroundColor Yellow
        $failed++
    }
}

Write-Host ""
Write-Host "=== SUMMARY ===" -ForegroundColor Cyan
Write-Host "Updated: $updated" -ForegroundColor Green
Write-Host "Failed/Skipped: $failed" -ForegroundColor Yellow
Write-Host ""

if ($updated -gt 0) {
    Write-Host "Deploying all updated endpoints..." -ForegroundColor Yellow
    pnpx supabase functions deploy
}
