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, appointment_date, appointment_time } =
      await req.json();
    if (!external_doctor_id || !appointment_date || !appointment_time) {
      throw new Error(
        "external_doctor_id, appointment_date, appointment_time required"
      );
    }

    // Buscar primeiro paciente na waitlist
    const { data: waitlistEntry } = await supabase
      .from("waitlist")
      .select("*")
      .eq("external_doctor_id", external_doctor_id)
      .eq("status", "waiting")
      .order("created_at", { ascending: true })
      .limit(1)
      .single();

    if (!waitlistEntry) {
      return new Response(
        JSON.stringify({
          success: true,
          data: { matched: false, message: "No patients in waitlist" },
        }),
        { headers: { ...corsHeaders, "Content-Type": "application/json" } }
      );
    }

    // Atualizar status da waitlist
    await supabase
      .from("waitlist")
      .update({ status: "matched", matched_at: new Date().toISOString() })
      .eq("id", waitlistEntry.id);

    return new Response(
      JSON.stringify({
        success: true,
        data: {
          matched: true,
          patient: waitlistEntry,
          suggested_appointment: { appointment_date, appointment_time },
        },
      }),
      { 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" },
      }
    );
  }
});
