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

    const { data, error } = await supabase
      .from("doctor_availability")
      .insert({
        external_doctor_id,
        day_of_week,
        start_time,
        end_time,
        slots_per_hour: slots_per_hour || 2,
        active: true,
        created_at: new Date().toISOString(),
      })
      .select()
      .single();

    if (error) throw error;

    await supabase.from("user_actions").insert({
      user_id: user.id,
      action: "create_availability",
      entity_type: "availability",
      entity_id: data.id,
      metadata: { external_doctor_id, day_of_week },
      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" },
      }
    );
  }
});
