# Script para criar e fazer deploy de todos os 36 endpoints faltantes
# Execute: .\deploy-all-endpoints.ps1

$baseDir = "C:\Users\raild\MEDICONNECT 13-11\riseup-squad18\supabase\functions"

# Template base para endpoints
$template = @"
// __DESCRIPTION__
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};

function externalRest(path: string, method: string = "GET", body?: any): Promise<any> {
  const url = `${Deno.env.get("EXTERNAL_SUPABASE_URL")}/rest/v1/${path}`;
  return fetch(url, {
    method,
    headers: {
      "Content-Type": "application/json",
      "apikey": Deno.env.get("EXTERNAL_SUPABASE_KEY")!,
      "Authorization": `Bearer ${Deno.env.get("EXTERNAL_SUPABASE_KEY")}`,
      "Prefer": "return=representation"
    },
    body: body ? JSON.stringify(body) : undefined
  }).then(r => r.json());
}

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });

  try {
    const authHeader = req.headers.get("Authorization");
    const supabase = createClient(
      Deno.env.get("SUPABASE_URL")!,
      Deno.env.get("SUPABASE_ANON_KEY")!,
      { global: { headers: { Authorization: authHeader! } } }
    );

    const { data: { user } } = await supabase.auth.getUser();
    if (!user) throw new Error("Unauthorized");

__LOGIC__

    return new Response(
      JSON.stringify({ success: true, data }),
      { headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );
  } catch (error: any) {
    return new Response(
      JSON.stringify({ success: false, error: error.message }),
      { status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );
  }
});
"@

# Lista de endpoints para criar
$endpoints = @(
    @{name="availability-create"; logic="    const body = await req.json();`n    const { data, error } = await supabase.from('doctor_availability').insert(body).select().single();`n    if (error) throw error;"},
    @{name="availability-update"; logic="    const body = await req.json();`n    const { id, ...updates } = body;`n    const { data, error } = await supabase.from('doctor_availability').update(updates).eq('id', id).select().single();`n    if (error) throw error;"},
    @{name="availability-delete"; logic="    const { id } = await req.json();`n    const { data, error } = await supabase.from('doctor_availability').update({is_active: false}).eq('id', id).select().single();`n    if (error) throw error;"},
    @{name="availability-slots"; logic="    const url = new URL(req.url);`n    const doctor_id = url.searchParams.get('doctor_id')!;`n    const { data, error } = await supabase.from('doctor_availability').select('*').eq('doctor_id', doctor_id).eq('is_active', true);`n    if (error) throw error;"},
    @{name="exceptions-list"; logic="    const url = new URL(req.url);`n    const doctor_id = url.searchParams.get('doctor_id');`n    let query = supabase.from('availability_exceptions').select('*');`n    if (doctor_id) query = query.eq('doctor_id', doctor_id);`n    const { data, error } = await query.order('exception_date');`n    if (error) throw error;"},
    @{name="exceptions-create"; logic="    const body = await req.json();`n    const { data, error } = await supabase.from('availability_exceptions').insert(body).select().single();`n    if (error) throw error;"},
    @{name="exceptions-delete"; logic="    const { id } = await req.json();`n    const { data, error } = await supabase.from('availability_exceptions').delete().eq('id', id);`n    if (error) throw error;"},
    @{name="waitlist-match"; logic="    const { doctor_id, appointment_date } = await req.json();`n    const { data, error } = await supabase.from('waitlist').select('*').eq('doctor_id', doctor_id).eq('status', 'waiting').order('priority', {ascending: false}).limit(1);`n    if (error) throw error;"},
    @{name="waitlist-remove"; logic="    const { id } = await req.json();`n    const { data, error } = await supabase.from('waitlist').update({status: 'cancelled'}).eq('id', id).select().single();`n    if (error) throw error;"},
    @{name="queue-checkin"; logic="    const { patient_id } = await req.json();`n    const { data, error } = await supabase.from('virtual_queue').insert({patient_id, status: 'waiting'}).select().single();`n    if (error) throw error;"},
    @{name="notifications-subscription"; logic="    const body = await req.json();`n    const { data, error } = await supabase.from('notification_subscriptions').upsert(body).select().single();`n    if (error) throw error;"},
    @{name="reports-list-extended"; logic="    const url = new URL(req.url);`n    const data = await externalRest('reports' + url.search);"},
    @{name="reports-export-csv"; logic="    const url = new URL(req.url);`n    const report_id = url.searchParams.get('report_id');`n    const data = await externalRest(`reports?id=eq.${report_id}`);"},
    @{name="reports-integrity-check"; logic="    const { report_id } = await req.json();`n    const { data, error } = await supabase.from('report_integrity').select('*').eq('report_id', report_id).single();`n    if (error) throw error;"},
    @{name="doctor-summary"; logic="    const url = new URL(req.url);`n    const doctor_id = url.searchParams.get('doctor_id') || user.id;`n    const { data, error } = await supabase.from('doctor_stats').select('*').eq('doctor_id', doctor_id).single();`n    if (error) throw error;"},
    @{name="doctor-occupancy"; logic="    const url = new URL(req.url);`n    const doctor_id = url.searchParams.get('doctor_id') || user.id;`n    const { data, error } = await supabase.from('doctor_stats').select('occupancy_rate').eq('doctor_id', doctor_id).single();`n    if (error) throw error;"},
    @{name="doctor-delay-suggestion"; logic="    const url = new URL(req.url);`n    const doctor_id = url.searchParams.get('doctor_id') || user.id;`n    const { data, error } = await supabase.from('doctor_stats').select('average_delay_minutes').eq('doctor_id', doctor_id).single();`n    if (error) throw error;"},
    @{name="patients-history"; logic="    const url = new URL(req.url);`n    const patient_id = url.searchParams.get('patient_id') || user.id;`n    const { data, error} = await supabase.from('patient_extended_history').select('*').eq('patient_id', patient_id).order('visit_date', {ascending: false});`n    if (error) throw error;"},
    @{name="patients-preferences"; logic="    const url = new URL(req.url);`n    const patient_id = url.searchParams.get('patient_id') || user.id;`n    const { data, error } = await supabase.from('patient_preferences').select('*').eq('patient_id', patient_id).single();`n    if (error) throw error;"},
    @{name="patients-portal"; logic="    const url = new URL(req.url);`n    const patient_id = url.searchParams.get('patient_id') || user.id;`n    const appointments = await externalRest(`appointments?patient_id=eq.${patient_id}&order=appointment_date.desc&limit=10`);`n    const { data: history } = await supabase.from('patient_extended_history').select('*').eq('patient_id', patient_id).limit(5);`n    const data = { appointments, history };"},
    @{name="analytics-heatmap"; logic="    const appointments = await externalRest('appointments?select=appointment_date,appointment_time');`n    const data = appointments;"},
    @{name="analytics-demand-curve"; logic="    const data = await externalRest('appointments?select=appointment_date&order=appointment_date');"},
    @{name="analytics-ranking-reasons"; logic="    const data = await externalRest('appointments?select=reason');"},
    @{name="analytics-monthly-no-show"; logic="    const data = await externalRest('appointments?status=eq.no_show&select=appointment_date');"},
    @{name="analytics-specialty-heatmap"; logic="    const { data, error } = await supabase.from('doctor_stats').select('*');`n    if (error) throw error;"},
    @{name="analytics-custom-report"; logic="    const body = await req.json();`n    const data = await externalRest(body.query);"},
    @{name="accessibility-preferences"; logic="    const body = await req.json();`n    const { data, error } = await supabase.from('user_preferences').upsert({user_id: user.id, ...body}).select().single();`n    if (error) throw error;"},
    @{name="audit-list"; logic="    const url = new URL(req.url);`n    const { data, error } = await supabase.from('audit_actions').select('*').order('timestamp', {ascending: false}).limit(100);`n    if (error) throw error;"},
    @{name="system-health-check"; logic="    const data = { status: 'healthy', timestamp: new Date().toISOString() };"},
    @{name="system-cache-rebuild"; logic="    const { data, error } = await supabase.from('analytics_cache').delete().neq('cache_key', '');`n    if (error) throw error;"},
    @{name="system-cron-runner"; logic="    const data = { status: 'executed', timestamp: new Date().toISOString() };"}
)

Write-Host "🚀 Criando $($endpoints.Count) endpoints..." -ForegroundColor Cyan

foreach ($endpoint in $endpoints) {
    $dirPath = Join-Path $baseDir $endpoint.name
    $filePath = Join-Path $dirPath "index.ts"
    
    # Criar diretório
    if (!(Test-Path $dirPath)) {
        New-Item -ItemType Directory -Path $dirPath -Force | Out-Null
    }
    
    # Criar arquivo
    $content = $template.Replace("__DESCRIPTION__", "ENDPOINT: /$($endpoint.name)").Replace("__LOGIC__", $endpoint.logic)
    Set-Content -Path $filePath -Value $content -Encoding UTF8
    
    Write-Host "✅ Criado: $($endpoint.name)" -ForegroundColor Green
}

Write-Host "`n📦 Iniciando deploy de todos os endpoints..." -ForegroundColor Cyan

# Deploy todos de uma vez
$functionNames = $endpoints | ForEach-Object { $_.name }
$functionList = $functionNames -join " "

Set-Location "C:\Users\raild\MEDICONNECT 13-11\riseup-squad18"
$deployCmd = "pnpx supabase functions deploy --no-verify-jwt $functionList"

Write-Host "Executando: $deployCmd" -ForegroundColor Yellow
Invoke-Expression $deployCmd

Write-Host "`n✨ Deploy concluído!" -ForegroundColor Green
Write-Host "Verifique com: pnpx supabase functions list" -ForegroundColor Cyan
