import { validateExternalAuth } from "../_shared/auth.ts";

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

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");

    const { external_doctor_id, date_from, date_to } = await req.json();
    if (!external_doctor_id) throw new Error("external_doctor_id required");

    // Buscar ou calcular stats
    const { data: stats } = await supabase
      .from("doctor_stats")
      .select("*")
      .eq("external_doctor_id", external_doctor_id)
      .single();

    // Se não existe, criar com valores default
    if (!stats) {
      const { data: newStats } = await supabase
        .from("doctor_stats")
        .insert({
          external_doctor_id,
          occupancy_rate: 0,
          no_show_count: 0,
          total_appointments: 0,
          average_delay_minutes: 0,
          created_at: new Date().toISOString(),
        })
        .select()
        .single();

      const data = { occupancy: 0, stats: newStats };
    } else {
      const data = { occupancy: stats.occupancy_rate, stats };
    }

    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" },
      }
    );
  }
});
