import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
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 {
    // External JWT comes in custom header (bypass Edge Runtime validation)
    const externalJwt = req.headers.get("x-external-jwt");
    if (!externalJwt) throw new Error("Missing x-external-jwt header");

    // Validar JWT no Supabase EXTERNO (source of truth for authentication)
    const externalSupabase = createClient(
      Deno.env.get("EXTERNAL_SUPABASE_URL")!,
      Deno.env.get("EXTERNAL_SUPABASE_ANON_KEY")!,
      { global: { headers: { Authorization: `Bearer ${externalJwt}` } } }
    );

    const {
      data: { user },
      error: authError,
    } = await externalSupabase.auth.getUser();
    if (authError || !user) {
      return new Response(
        JSON.stringify({
          success: false,
          error: "Invalid external JWT",
          details: authError?.message,
        }),
        {
          status: 401,
          headers: { ...corsHeaders, "Content-Type": "application/json" },
        }
      );
    }

    // Cliente para NOSSO Supabase (service_role = sem validação de JWT)
    const supabase = createClient(
      Deno.env.get("SUPABASE_URL")!,
      Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
    );

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

    // 1. Buscar appointments de HOJE do Supabase EXTERNO
    const today = new Date().toISOString().split("T")[0];
    const externalAppointments = await getExternalAppointments(
      { doctor_id, date: today },
      `Bearer ${externalJwt}`
    );

    // 2. Buscar stats do NOSSO Supabase
    const { data: stats } = await supabase
      .from("doctor_stats")
      .select("*")
      .eq("external_doctor_id", doctor_id)
      .single();

    // 3. Buscar badges do NOSSO Supabase
    const { data: badges } = await supabase
      .from("doctor_badges")
      .select("*")
      .eq("external_doctor_id", doctor_id);

    // 4. Mesclar dados
    const summary = {
      doctor_id,
      today: {
        total_appointments: externalAppointments.length,
        completed: externalAppointments.filter(
          (a: any) => a.status === "completed"
        ).length,
        pending: externalAppointments.filter(
          (a: any) => a.status === "scheduled"
        ).length,
        no_show: externalAppointments.filter((a: any) => a.status === "no_show")
          .length,
      },
      stats: stats || {},
      badges: badges || [],
      appointments: externalAppointments,
    };

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