const {
  toFiniteNumber
} = require('./calculation-context')

function getInputTextWithoutUnit(item, value) {
  const text = String(value === undefined || value === null ? '' : value).trim()
  if (!item || !item.unit || !text) return text

  const lowerText = text.toLowerCase()
  const lowerUnit = String(item.unit).toLowerCase()

  return lowerText.endsWith(lowerUnit)
    ? text.slice(0, -item.unit.length).trim()
    : text
}

function appendInputUnit(item, value) {
  const text = String(value === undefined || value === null ? '' : value).trim()
  if (!item || !item.unit || !text) return text

  const valueText = getInputTextWithoutUnit(item, text)
  if (!Number.isFinite(toFiniteNumber(valueText, NaN))) return text

  return `${valueText} ${item.unit}`
}

module.exports = {
  appendInputUnit
}
