import { Alignment, pad } from '../../../string'
import { ZASection } from '../../../types'

// Format a single ZA record into a padded string
export function formatZARecord(za: ZASection): string {
  return [
    pad(za.date, 8),
    pad(za.code, 7),
    formatZAExt(za.ext),
    pad(za.phase ?? '', 1),
    pad(za.act ?? '', 1),
    pad(za.diag ?? '', 1),
    pad(za.mod ?? '', 4),
    pad(za.RE ?? '', 1),
    pad(za.AN ?? '', 1),
    pad(za.qty ?? '', 2, Alignment.RIGHT, '0')
  ].join('')
}

export const formatZAExt = (ext: ZASection['ext']): string => {
  if (!ext) return '   '

  switch (ext.length) {
    case 1:
      return `-0${ext}`
    case 2:
      return `-${ext}`
    case 3:
      if (ext.startsWith('-')) return `${ext}`
      throw new Error(`Invalid ZA ext length: ${ext}`)
    default:
      throw new Error(`Invalid ZA ext length: ${ext}`)
  }
}
