/**
 * INI.txt builder — uniform-format-export (wave-13, spec 180).
 *
 * INI.txt is the index file sent alongside BKMVDATA.txt.
 * It repeats the A000 header and lists each record type with its count.
 * When journal counts (B100/B110) are zero, the export is flagged as
 * documents-only (ערכים בלבד) per ITA rules.
 */
import type { A000Header, UniformRecordCode } from './types'
import { buildA000 } from './records'
import { textField, numField } from './records'

const RECORD_CODES: UniformRecordCode[] = ['A000', 'A100', 'C100', 'D110', 'D120', 'B100', 'B110', 'M100', 'Z900']

/**
 * Build INI.txt lines.
 * Returns an array of strings, one per line (without line endings).
 * Callers should join with CRLF and encode via CP1255.
 */
export function buildINI(header: A000Header, counts: Record<UniformRecordCode, number>): string[] {
  const lines: string[] = []

  // Header line: same as A000
  lines.push(buildA000(header))

  // Documents-only flag: when journal counts are 0
  const hasJournal = (counts['B100'] ?? 0) > 0 || (counts['B110'] ?? 0) > 0
  const modeFlag = hasJournal ? textField('', 20) : textField('ערכים בלבד', 20) // ערכים בלבד

  lines.push(`AINI${modeFlag}`)

  // One summary line per record type code
  for (const code of RECORD_CODES) {
    const count = counts[code] ?? 0
    // Format: code (4) + count (15)
    lines.push(`${code}${numField(count, 15)}`)
  }

  return lines
}
