import { ICraftableItem, IItemContainer } from '@rpg-engine/shared';
import { countItemFromInventory } from '../../../libs/itemCounter';

export function calculateMaxCraftable(
  recipe: ICraftableItem | undefined,
  inventory: IItemContainer | null | undefined
): number {
  if (!inventory || !recipe?.ingredients) {
    return 0;
  }

  return (
    recipe.ingredients.reduce((maxPossible, ingredient) => {
      const totalQty = countItemFromInventory(ingredient.key, inventory);

      if (totalQty === 0) {
        return 0;
      }

      const possibleWithThisIngredient = Math.floor(totalQty / ingredient.qty);

      return maxPossible === undefined
        ? possibleWithThisIngredient
        : Math.min(maxPossible, possibleWithThisIngredient);
    }, undefined as number | undefined) ?? 0
  );
}
