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_report_id, content } = await req.json();
    if (!external_report_id || !content)
      throw new Error("external_report_id and content required");

    // Gerar hash SHA256
    const encoder = new TextEncoder();
    const data_buffer = encoder.encode(content);
    const hash_buffer = await crypto.subtle.digest("SHA-256", data_buffer);
    const hash_array = Array.from(new Uint8Array(hash_buffer));
    const sha256_hash = hash_array
      .map((b) => b.toString(16).padStart(2, "0"))
      .join("");

    // Salvar integrity
    const { data, error } = await supabase
      .from("report_integrity")
      .upsert(
        {
          external_report_id,
          sha256_hash,
          verified_at: new Date().toISOString(),
        },
        { onConflict: "external_report_id" }
      )
      .select()
      .single();

    if (error) throw error;

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