export function parseAmountToFen(value: unknown): number {
  const normalized = normalizeAmountInput(value)

  if (!normalized) {
    return 0
  }

  const sign = normalized.startsWith('-') ? -1 : 1
  const unsigned = sign < 0 ? normalized.slice(1) : normalized
  const match = unsigned.match(/^(\d+)(?:\.(\d+))?$/)

  if (!match) {
    return 0
  }

  const integerPart = Number(match[1] || '0')

  if (!Number.isSafeInteger(integerPart)) {
    return 0
  }

  const fractionRaw = String(match[2] || '')
  const fractionForRound = `${fractionRaw}000`
  let cents = integerPart * 100 + Number(fractionForRound.slice(0, 2))

  if (Number(fractionForRound[2] || '0') >= 5) {
    cents += 1
  }

  return cents * sign
}

export function formatFenToAmount(value: unknown): string {
  const normalizedFen = normalizeFen(value)
  const sign = normalizedFen < 0 ? '-' : ''
  const absoluteFen = Math.abs(normalizedFen)
  const integerPart = Math.floor(absoluteFen / 100)
  const fractionPart = String(absoluteFen % 100).padStart(2, '0')
  return `${sign}${integerPart}.${fractionPart}`
}

export function normalizeFen(value: unknown): number {
  const parsed = Number(value)
  return Number.isFinite(parsed) ? Math.round(parsed) : 0
}

function normalizeAmountInput(value: unknown): string {
  if (typeof value === 'number' && Number.isFinite(value)) {
    return String(value)
  }

  if (typeof value !== 'string') {
    return ''
  }

  return value.trim().replace(/,/g, '')
}
