import { validateExternalAuth } from "../_shared/auth.ts";
import { getExternalReports } 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 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 { patient_id, doctor_id, date_from, date_to } = await req.json();

    // 1. Buscar reports do Supabase EXTERNO
    const externalReports = await getExternalReports(
      { patient_id, doctor_id, date_from, date_to },
      authHeader!
    );

    // 2. Para cada report, buscar integrity hash do NOSSO Supabase
    const reportIds = externalReports.map((r: any) => r.id);
    const { data: integrityData } = await supabase
      .from("report_integrity")
      .select("*")
      .in("external_report_id", reportIds);

    // 3. Mesclar dados
    const reportsWithIntegrity = externalReports.map((report: any) => {
      const integrity = integrityData?.find(
        (i: any) => i.external_report_id === report.id
      );
      return {
        ...report,
        has_integrity_check: !!integrity,
        verified_at: integrity?.verified_at || null,
        hash: integrity?.sha256_hash || null,
      };
    });

    return new Response(
      JSON.stringify({
        success: true,
        data: {
          reports: reportsWithIntegrity,
          total: reportsWithIntegrity.length,
          verified: reportsWithIntegrity.filter(
            (r: any) => r.has_integrity_check
          ).length,
        },
      }),
      { 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" },
      }
    );
  }
});
