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 { patient_id, date_from, date_to } = await req.json();

    // Buscar reports (simulação - deveria vir do externo)
    const { data: reports } = await supabase
      .from("patient_extended_history")
      .select("*")
      .eq("external_patient_id", patient_id || user.id)
      .order("created_at", { ascending: false });

    // Gerar CSV
    let csv = "Date,Type,Description,Doctor\n";
    reports?.forEach((r: any) => {
      csv += `${r.created_at},${r.type || "N/A"},${r.notes || "N/A"},${
        r.external_doctor_id || "N/A"
      }\n`;
    });

    return new Response(csv, {
      headers: {
        ...corsHeaders,
        "Content-Type": "text/csv",
        "Content-Disposition": "attachment; filename=reports.csv",
      },
    });

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