import type { PartyMember, Spell } from '../game'
import { putSpellOnCooldown } from './spellCasting'
import { advanceFreeCastProgress } from './spellEffects'

export type CastStateFields<TParty extends readonly PartyMember[] = PartyMember[]> = {
  party: TParty
  resource: number
  cooldowns: Record<string, number>
  castsTowardFree: number
  freeCastReady: boolean
}

export function applyCastStateUpdate<
  TParty extends readonly PartyMember[],
  TState extends CastStateFields<TParty>,
>({
  current,
  party,
  spell,
  resourceCost,
  cooldownMultiplier = 1,
  cooldowns = current.cooldowns,
  freeCast = { enabled: false, wasReady: false },
}: {
  current: TState
  party: TParty
  spell: Spell
  resourceCost: number
  cooldownMultiplier?: number
  cooldowns?: Record<string, number>
  freeCast?: {
    enabled: boolean
    wasReady: boolean
  }
}) {
  const freeCastProgress = advanceFreeCastProgress({
    enabled: freeCast.enabled,
    wasReady: freeCast.wasReady,
    castsTowardFree: current.castsTowardFree,
  })

  return {
    ...current,
    party,
    resource: current.resource - resourceCost,
    cooldowns: putSpellOnCooldown(cooldowns, spell, cooldownMultiplier),
    castsTowardFree: freeCastProgress.castsTowardFree,
    freeCastReady: freeCastProgress.freeCastReady,
  }
}
