/**
 * Proposal PDF totals computation — proposal-pdf-export.
 * Pure function: no I/O, no side effects.
 */
import type { ProposalContent } from '@zync/types'

// ── Types ─────────────────────────────────────────────────────────────────────

export interface ProposalTotalsLine {
  description: string
  quantity: number
  unitPrice: number
  lineSubtotal: number
}

export interface ProposalTotals {
  currency: string
  lines: ProposalTotalsLine[]
  subtotalExclVat: number
  discountPct: number
  discountAmount: number
  vatRate: number
  vatTotal: number
  grandTotal: number
  showLineTax: boolean
  showSubtotal: boolean
}

// ── computeProposalTotals ─────────────────────────────────────────────────────

/**
 * Compute pricing totals for a proposal.
 * @param content - The structured proposal content (JSONB).
 * @param tenantVatRate - Decimal fraction e.g. 0.18 for 18%; pass 0 for no VAT.
 */
export function computeProposalTotals(
  content: ProposalContent,
  tenantVatRate: number,
): ProposalTotals {
  const { sections, settings } = content
  const { currency, discount_pct, show_line_tax, show_subtotal } = settings

  // Collect all line items from line_items sections
  const lines: ProposalTotalsLine[] = []
  for (const section of sections) {
    if (section.type !== 'line_items') continue
    for (const item of section.items) {
      const lineSubtotal = item.quantity * item.unit_price
      lines.push({
        description: item.description,
        quantity: item.quantity,
        unitPrice: item.unit_price,
        lineSubtotal,
      })
    }
  }

  // Sum before discount
  const rawSubtotal = lines.reduce((acc, l) => acc + l.lineSubtotal, 0)

  // Discount
  const discountPct = discount_pct ?? 0
  const discountAmount = rawSubtotal * (discountPct / 100)
  const subtotalExclVat = rawSubtotal - discountAmount

  // VAT applied to subtotal after discount
  const vatTotal = subtotalExclVat * tenantVatRate
  const grandTotal = subtotalExclVat + vatTotal

  return {
    currency,
    lines,
    subtotalExclVat,
    discountPct,
    discountAmount,
    vatRate: tenantVatRate,
    vatTotal,
    grandTotal,
    showLineTax: show_line_tax,
    showSubtotal: show_subtotal,
  }
}
