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";
import { validateAuth, hasPermission } from "../../lib/auth.ts";

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

  try {
    // Validar autenticação
    const auth = await validateAuth(req);
    if (!auth) {
      return errorResponse("Não autorizado", 401);
    }

    // Apenas admin, secretária e médico podem ver analytics
    if (!hasPermission(auth.role, ["admin", "secretary", "doctor"])) {
      return errorResponse("Sem permissão para acessar analytics", 403);
    }

    // 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);
  }
});
