 function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }import { asNumber, asObject, asOptional, asString, } from 'cleaners'



export const asEdgeMetadata = raw => {
  const clean = asDiskMetadata(raw)
  const { exchangeAmount = {} } = clean

  // Delete corrupt amounts that exceed the Javascript number range:
  for (const fiat of Object.keys(exchangeAmount)) {
    if (String(exchangeAmount[fiat]).includes('e')) {
      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
      delete exchangeAmount[fiat]
    }
  }

  return clean
}

export function mergeMetadata(
  under,
  over
) {
  const out = { exchangeAmount: {} }
  const { exchangeAmount = {} } = out

  // Merge the fiat amounts:
  const underAmounts = _nullishCoalesce(under.exchangeAmount, () => ( {}))
  const overAmounts = _nullishCoalesce(over.exchangeAmount, () => ( {}))
  for (const fiat of Object.keys(underAmounts)) {
    if (overAmounts[fiat] !== null) exchangeAmount[fiat] = underAmounts[fiat]
  }
  for (const fiat of Object.keys(overAmounts)) {
    const amount = overAmounts[fiat]
    if (amount != null) exchangeAmount[fiat] = amount
  }

  // Merge simple fields:
  if (over.bizId !== null) out.bizId = _nullishCoalesce(over.bizId, () => ( under.bizId))
  if (over.category !== null) out.category = _nullishCoalesce(over.category, () => ( under.category))
  if (over.name !== null) out.name = _nullishCoalesce(over.name, () => ( under.name))
  if (over.notes !== null) out.notes = _nullishCoalesce(over.notes, () => ( under.notes))

  return out
}

const asDiskMetadata = asObject({
  bizId: asOptional(asNumber),
  category: asOptional(asString),
  exchangeAmount: asOptional(asObject(asNumber)),
  name: asOptional(asString),
  notes: asOptional(asString)
})
