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;

    if (req.method === "GET") {
      const url = new URL(req.url);
      const external_patient_id =
        url.searchParams.get("external_patient_id") || user.id;

      const { data, error } = await supabase
        .from("patient_preferences")
        .select("*")
        .eq("external_patient_id", external_patient_id)
        .single();

      if (error && error.code !== "PGRST116") throw error;
      return new Response(JSON.stringify({ success: true, data: data || {} }), {
        headers: { ...corsHeaders, "Content-Type": "application/json" },
      });
    }

    const {
      external_patient_id,
      preferred_days,
      preferred_times,
      preferred_doctor_id,
      communication_channel,
    } = await req.json();

    const { data, error } = await supabase
      .from("patient_preferences")
      .upsert(
        {
          external_patient_id: external_patient_id || user.id,
          preferred_days,
          preferred_times,
          preferred_doctor_id,
          communication_channel,
          updated_at: new Date().toISOString(),
        },
        { onConflict: "external_patient_id" }
      )
      .select()
      .single();

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