import { serve } from "https://deno.land/std@0.168.0/http/server.ts"; import { externalRest } from "../../lib/externalSupabase.ts"; import { mydb } from "../../lib/mySupabase.ts"; import { corsHeaders, jsonResponse, errorResponse } from "../../lib/utils.ts"; serve(async (req) => { // Handle CORS preflight if (req.method === "OPTIONS") { return new Response("ok", { status: 200, headers: corsHeaders() }); } try { // Analytics sempre retorna o sumário (GET ou POST) // Buscar appointments do Supabase externo const ext = await externalRest("/rest/v1/appointments", "GET"); if (ext.status >= 400) { return errorResponse("External fetch failed"); } const appts = ext.data; // Calcular KPIs const total = appts.length; const today = appts.filter( (a: any) => a.date === new Date().toISOString().slice(0, 10) ).length; const canceled = appts.filter((a: any) => a.status === "canceled").length; const completed = appts.filter((a: any) => a.status === "completed").length; const summary = { total_appointments: total, today, canceled, completed, pending: total - canceled - completed, updated_at: new Date().toISOString(), }; // Salvar em cache await mydb.from("kpi_cache").upsert({ key: "summary", value: summary, updated_at: new Date().toISOString(), }); return jsonResponse(summary); } catch (error) { console.error("Error in analytics function:", error); return errorResponse(error.message); } });