/**
 * pcn874-csv.ts — PCN874 machine-readable CSV writer for ITA portal upload.
 *
 * Output encoding: CP1255 (Windows-Hebrew) — the ITA/shaam.gov.il portal
 * expects this encoding. Emitting UTF-8 corrupts Hebrew names on upload.
 * The raw Uint8Array is returned; callers must NOT re-encode to UTF-8.
 *
 * PCN874 record layout (ITA summary pre-fill format):
 *   Header record: H,business_tax_id,period_YYYYMM,vat_period,net_output_vat,net_input_vat,vat_payable
 *   Output records: O,<turnover_ils>,<vat_ils>
 *   Credit records: C,<turnover_ils>,<vat_ils>
 *   Input records: I,<expense_total_ils>,<input_vat_ils>
 *
 * Spec: 2026-06-01-israeli-tax-reports (wave-14)
 */
import { encodeCP1255 } from './cp1255'
import { sanitizeCell, toCsvRow } from './financial-export'
import type { Pcn874Report } from '@zync/types'

/**
 * Build the PCN874 CSV as CP1255-encoded bytes.
 * Returns a Uint8Array that must be written directly to the response body
 * with Content-Type: text/csv; charset=windows-1255 — no UTF-8 re-encoding.
 */
export function buildPcn874Csv(
  report: Pcn874Report,
  tenant: { businessTaxId: string },
): Uint8Array {
  const lines: string[] = []
  const periodYYYYMM = report.periodFrom.replace(/-/g, '').slice(0, 6)

  // ── Header record ──
  lines.push(
    toCsvRow(
      [
        'H',
        sanitizeCell(tenant.businessTaxId) as string,
        periodYYYYMM,
        report.vatPeriod,
        report.netOutputVatIls,
        report.netInputVatIls,
        report.vatPayableIls,
      ],
      { sanitize: false },
    ),
  )

  // ── Output VAT record ──
  lines.push(
    toCsvRow(
      [
        'O',
        report.outputTurnoverIls,
        report.outputVatIls,
        String(report.outputInvoiceCount),
      ],
      { sanitize: false },
    ),
  )

  // ── Credit note record ──
  if (report.creditNoteCount > 0) {
    lines.push(
      toCsvRow(
        [
          'C',
          report.creditNoteTurnoverIls,
          report.creditNoteVatIls,
          String(report.creditNoteCount),
        ],
        { sanitize: false },
      ),
    )
  }

  // ── Input VAT record ──
  lines.push(
    toCsvRow(
      [
        'I',
        report.inputExpenseTotalIls,
        report.inputVatIls,
        String(report.inputExpenseCount),
      ],
      { sanitize: false },
    ),
  )

  // ITA expects CRLF line endings; encode entire content as CP1255
  const csvText = lines.join('\r\n') + '\r\n'
  return encodeCP1255(csvText)
}
