import { moneyTotal } from '../../utils/moneyTotal.js'
import { EXPERIENCE_VALUES, PURCHASEABLE_CELLARS } from '../../constants.js'

import { CELLAR_PURCHASED } from '../../templates.js'

import { addExperience } from './addExperience.js'
import { showNotification } from './showNotification.js'

export const purchaseCellar = (
  state: farmhand.state,
  cellarId: number
): farmhand.state => {
  const { money, purchasedCellar } = state

  if (purchasedCellar >= cellarId) {
    return state
  }

  const cellarData = PURCHASEABLE_CELLARS.get(cellarId)

  if (!cellarData) {
    return state
  }

  const { price, space } = cellarData

  state = showNotification(state, CELLAR_PURCHASED('', space), 'success')

  const experienceEarned =
    cellarId > 1
      ? EXPERIENCE_VALUES.CELLAR_EXPANDED
      : EXPERIENCE_VALUES.CELLAR_ACQUIRED

  state = addExperience(state, experienceEarned)

  return {
    ...state,
    purchasedCellar: cellarId,
    money: moneyTotal(money, -price),
  }
}
