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 authHeader = req.headers.get("Authorization");
    const supabase = createClient(
      Deno.env.get("SUPABASE_URL")!,
      Deno.env.get("SUPABASE_ANON_KEY")!,
      { global: { headers: { Authorization: authHeader! } } }
    );

    const {
      data: { user },
    } = await supabase.auth.getUser();
    if (!user) throw new Error("Unauthorized");

    const external_patient_id = user.id;

    // Buscar histórico estendido
    const { data: history } = await supabase
      .from("patient_extended_history")
      .select("*")
      .eq("external_patient_id", external_patient_id)
      .order("created_at", { ascending: false })
      .limit(10);

    // Buscar preferências
    const { data: preferences } = await supabase
      .from("patient_preferences")
      .select("*")
      .eq("external_patient_id", external_patient_id)
      .single();

    // Buscar teleconsultas
    const { data: teleconsults } = await supabase
      .from("teleconsult_sessions")
      .select("*")
      .eq("external_patient_id", external_patient_id)
      .order("created_at", { ascending: false })
      .limit(5);

    const data = {
      patient_id: external_patient_id,
      history: history || [],
      preferences: preferences || {},
      teleconsults: teleconsults || [],
    };

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