/**
 * AR Aging CSV formatter — ar-aging-report (wave-12).
 *
 * Produces UTF-8 BOM CSV for Excel/Hebrew compatibility.
 * Layout: summary header row + one row per customer.
 */
import type { ArAgingReport } from '@zync/types'
import { sanitizeCell } from './financial-export'

function csvEscape(val: string | number): string {
  const s = typeof val === 'string' ? (sanitizeCell(val) as string) : String(val)
  if (s.includes(',') || s.includes('"') || s.includes('\n')) {
    return '"' + s.replace(/"/g, '""') + '"'
  }
  return s
}

function csvRow(cols: (string | number)[]): string {
  return cols.map(csvEscape).join(',')
}

export function buildArAgingCsv(report: ArAgingReport): string {
  const BOM = '﻿'

  const lines: string[] = []

  // Header comment
  lines.push(csvRow([`AR Aging Report — as of ${report.asOf} — Currency: ${report.currency}`]))
  lines.push('')

  // Column headers
  lines.push(csvRow(['Customer', 'Current', '1-30 Days', '31-60 Days', '61-90 Days', '90+ Days', 'Total']))

  // Summary row
  const s = report.summary
  lines.push(csvRow([
    'TOTAL',
    s.current.amount,
    s.d1_30.amount,
    s.d31_60.amount,
    s.d61_90.amount,
    s.d90plus.amount,
    s.total,
  ]))

  lines.push('')

  // Per-customer rows
  for (const cust of report.customers) {
    lines.push(csvRow([
      cust.customerName,
      cust.current.amount,
      cust.d1_30.amount,
      cust.d31_60.amount,
      cust.d61_90.amount,
      cust.d90plus.amount,
      cust.total,
    ]))
  }

  return BOM + lines.join('\r\n')
}
