import { supabase } from "@/integrations/supabase/client";

/**
 * Saves a bill's invoice PDF to the Documents table under the "Vendor Invoices"
 * folder for the assigned association/client. Fire-and-forget; logs on failure
 * but does not throw so the bill creation flow is never blocked.
 */
export async function saveBillInvoiceToDocuments(params: {
  associationId: string | null | undefined;
  attachmentUrl: string | null | undefined;
  vendorName?: string | null;
  invoiceNumber?: string | null;
  invoiceDate?: string | null;
  uploadedBy?: string | null;
}): Promise<void> {
  try {
    const { associationId, attachmentUrl } = params;
    if (!associationId || !attachmentUrl) return;

    const vendor = (params.vendorName || "Unknown Vendor").trim();
    const inv = params.invoiceNumber ? ` #${params.invoiceNumber}` : "";
    const dateSuffix = params.invoiceDate
      ? ` (${params.invoiceDate})`
      : "";
    const title = `${vendor} Invoice${inv}${dateSuffix}`.slice(0, 250);

    // Derive a sensible file_name from the URL
    let fileName = "invoice.pdf";
    try {
      const u = new URL(attachmentUrl);
      const last = u.pathname.split("/").pop();
      if (last) fileName = decodeURIComponent(last);
    } catch {
      /* ignore */
    }

    // Avoid duplicate inserts if this same attachment was already filed
    const { data: existing } = await supabase
      .from("documents")
      .select("id")
      .eq("association_id", associationId)
      .eq("file_url", attachmentUrl)
      .maybeSingle();
    if (existing?.id) return;

    const { error } = await supabase.from("documents").insert({
      title,
      association_id: associationId,
      category: "Vendor Invoices",
      file_name: fileName,
      file_url: attachmentUrl,
      uploaded_by: params.uploadedBy || null,
    });
    if (error) console.warn("[saveBillInvoiceToDocuments] insert failed:", error);
  } catch (err) {
    console.warn("[saveBillInvoiceToDocuments] unexpected error:", err);
  }
}