// MÓDULO 2.2: AVAILABILITY - /availability/list
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 url = new URL(req.url);
    const doctor_id = url.searchParams.get("doctor_id");

    let query = supabase
      .from("doctor_availability")
      .select("*")
      .eq("is_active", true);
    if (doctor_id) query = query.eq("doctor_id", doctor_id);

    const { data, error } = await query
      .order("day_of_week")
      .order("start_time");
    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" },
      }
    );
  }
});
