import { validateExternalAuth } from "../_shared/auth.ts";
import { getExternalAppointments } from "../_shared/external.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 externalJwt = req.headers.get("x-external-jwt")!;

    const { patient_id } = await req.json();
    if (!patient_id) throw new Error("patient_id required");

    // 1. Buscar appointments do Supabase EXTERNO
    const externalAppointments = await getExternalAppointments(
      { patient_id },
      `Bearer ${externalJwt}`
    );

    // 2. Buscar histórico estendido do NOSSO Supabase
    const { data: extendedHistory } = await supabase
      .from("patient_extended_history")
      .select("*")
      .eq("external_patient_id", patient_id)
      .order("created_at", { ascending: false });

    // 3. Buscar journey do paciente
    const { data: journey } = await supabase
      .from("patient_journey")
      .select("*")
      .eq("external_patient_id", patient_id)
      .order("timestamp", { ascending: false });

    // 4. Mesclar dados
    const history = {
      patient_id,
      appointments: externalAppointments,
      extended_history: extendedHistory || [],
      journey: journey || [],
      summary: {
        total_appointments: externalAppointments.length,
        completed: externalAppointments.filter(
          (a: any) => a.status === "completed"
        ).length,
        no_show: externalAppointments.filter((a: any) => a.status === "no_show")
          .length,
        upcoming: externalAppointments.filter(
          (a: any) => a.status === "scheduled"
        ).length,
      },
    };

    return new Response(JSON.stringify({ success: true, data: history }), {
      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" },
      }
    );
  }
});
