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 { id, start_time, end_time, slots_per_hour, active } =
      await req.json();
    if (!id) throw new Error("id required");

    const updateData: any = { updated_at: new Date().toISOString() };
    if (start_time) updateData.start_time = start_time;
    if (end_time) updateData.end_time = end_time;
    if (slots_per_hour !== undefined)
      updateData.slots_per_hour = slots_per_hour;
    if (active !== undefined) updateData.active = active;

    const { data, error } = await supabase
      .from("doctor_availability")
      .update(updateData)
      .eq("id", id)
      .select()
      .single();

    if (error) throw error;

    await supabase.from("user_actions").insert({
      user_id: user.id,
      action: "update_availability",
      entity_type: "availability",
      entity_id: id,
      metadata: updateData,
      created_at: new Date().toISOString(),
    });

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