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 url = new URL(req.url);
    const external_doctor_id = url.searchParams.get("external_doctor_id");
    const date_from = url.searchParams.get("date_from");
    const date_to = url.searchParams.get("date_to");

    let query = supabase.from("availability_exceptions").select("*");

    if (external_doctor_id)
      query = query.eq("external_doctor_id", external_doctor_id);
    if (date_from) query = query.gte("exception_date", date_from);
    if (date_to) query = query.lte("exception_date", date_to);

    const { data, error } = await query.order("exception_date", {
      ascending: true,
    });
    if (error) throw error;

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