
/**
 * PDF Generation Utility: exportUnitLedgerToPdf
 * 
 * Expected Usage:
 * Generates a basic tabular PDF ledger report for a specific unit using jsPDF.
 * 
 * Troubleshooting Blank PDFs:
 * - Ensure `transactions` array is passed and populated.
 * - Throws error if `transactions` is empty to prevent blank document generation.
 */

import { jsPDF } from 'jspdf';
import autoTable from 'jspdf-autotable';
import { format } from 'date-fns';

export const exportUnitLedgerToPdf = (unit, transactions) => {
  if (!transactions || transactions.length === 0) {
      throw new Error("No transactions available to export for this ledger.");
  }

  const doc = new jsPDF({ compress: true });
  
  doc.setFontSize(18);
  doc.text(`Unit Ledger: ${unit?.owner_name || 'Unknown Owner'}`, 14, 20);
  
  doc.setFontSize(11);
  doc.text(`Unit: ${unit?.unit_id || 'N/A'}`, 14, 28);
  doc.text(`Address: ${unit?.property_address || 'N/A'}`, 14, 34);
  doc.text(`Current Balance: $${(unit?.balance || 0).toFixed(2)}`, 14, 40);
  doc.text(`Generated on: ${format(new Date(), 'MMM dd, yyyy HH:mm a')}`, 14, 46);

  const tableColumn = ["Date", "Description", "Type", "Category", "Debit", "Credit", "Balance"];
  const tableRows = [];

  transactions.forEach(t => {
    tableRows.push([
      format(new Date(t.transaction_date), 'MMM dd, yyyy'),
      t.description || '',
      t.transaction_type || '',
      t.category || '',
      t.debit_credit === 'debit' ? `$${parseFloat(t.amount).toFixed(2)}` : '',
      t.debit_credit === 'credit' ? `$${parseFloat(t.amount).toFixed(2)}` : '',
      `$${parseFloat(t.runningBalance || 0).toFixed(2)}`
    ]);
  });

  autoTable(doc, {
    startY: 55,
    head: [tableColumn],
    body: tableRows,
    theme: 'grid',
    headStyles: { fillColor: [51, 65, 85] },
    styles: { fontSize: 9 },
    columnStyles: {
      4: { halign: 'right' },
      5: { halign: 'right' },
      6: { halign: 'right', fontStyle: 'bold' }
    }
  });

  const safeDate = format(new Date(), 'yyyy-MM-dd');
  doc.save(`Unit_Ledger_${unit?.unit_id || 'Report'}_${safeDate}.pdf`);
  return true;
};
