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

    const { error } = await supabase
      .from("doctor_availability")
      .delete()
      .eq("id", id);

    if (error) throw error;

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

    const data = { success: true, message: "Availability deleted" };

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