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 { user, ownSupabase } = await validateExternalAuth(req);
    const supabase = ownSupabase;

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

    const dayOfWeek = new Date(date).getDay();

    // 1. Buscar disponibilidade do médico
    const { data: availability } = await supabase
      .from("doctor_availability")
      .select("*")
      .eq("external_doctor_id", external_doctor_id)
      .eq("day_of_week", dayOfWeek)
      .eq("active", true);

    // 2. Verificar exceções
    const { data: exceptions } = await supabase
      .from("availability_exceptions")
      .select("*")
      .eq("external_doctor_id", external_doctor_id)
      .eq("exception_date", date);

    if (exceptions && exceptions.length > 0) {
      return new Response(
        JSON.stringify({
          success: true,
          data: { slots: [], reason: "Exception date" },
        }),
        { headers: { ...corsHeaders, "Content-Type": "application/json" } }
      );
    }

    // 3. Gerar slots
    const slots = [];
    if (availability) {
      for (const avail of availability) {
        const start = parseInt(avail.start_time.split(":")[0]);
        const end = parseInt(avail.end_time.split(":")[0]);
        for (let hour = start; hour < end; hour++) {
          slots.push({
            time: `${hour.toString().padStart(2, "0")}:00`,
            available: true,
          });
        }
      }
    }

    const data = { slots, date, day_of_week: dayOfWeek };

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