import { supabase } from "@/integrations/supabase/client";
import type jsPDF from "jspdf";
import { buildSecureStorageKey } from "@/lib/secureStorageNaming";

/**
 * Uploads the jsPDF document to storage and links it to a validation proof record.
 * Call this AFTER embedValidationProof() returns the proof, but BEFORE doc.save().
 *
 * The original `fileName` is kept only for callers that want to reference it
 * (and is recorded on the validation proof record). The actual storage key is
 * randomized so the public URL doesn't leak the document's real name.
 */
export async function storeValidatedPdf(
  doc: jsPDF,
  proofId: string,
  fileName: string,
): Promise<string | null> {
  try {
    const blob = doc.output("blob");
    const storagePath = buildSecureStorageKey("doc.pdf", `validated-docs/${proofId}`);
    const buckets = ["proof-files", "files"];
    let publicUrl: string | null = null;
    let lastUploadError: unknown = null;

    for (const bucket of buckets) {
      const { error: uploadErr } = await supabase.storage
        .from(bucket)
        .upload(storagePath, blob, { contentType: "application/pdf", upsert: true });

      if (!uploadErr) {
        const { data } = supabase.storage.from(bucket).getPublicUrl(storagePath);
        publicUrl = data.publicUrl;
        break;
      }

      lastUploadError = uploadErr;
    }

    if (!publicUrl) {
      console.error("[storeValidatedPdf] Upload error:", lastUploadError);
      return null;
    }

    // Update the validation proof record with the file URL and original name
    const { error: updateErr } = await supabase
      .from("document_validation_proofs")
      .update({ file_url: publicUrl, file_name: fileName } as any)
      .eq("id", proofId);

    if (updateErr) {
      console.error("[storeValidatedPdf] DB update error:", updateErr);
    }

    console.log(`[storeValidatedPdf] PDF stored: ${publicUrl}`);
    return publicUrl;
  } catch (err) {
    console.error("[storeValidatedPdf] Unexpected error:", err);
    return null;
  }
}
