import { ICraftableItem, IItem, IItemContainer } from '@rpg-engine/shared';

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

  return (
    recipe.ingredients.reduce((maxPossible, ingredient) => {
      const inventoryItem = Object.values(inventory.slots).find(
        (item): item is IItem => item?.key === ingredient.key
      );

      if (!inventoryItem) {
        return 0;
      }

      const possibleWithThisIngredient = Math.floor(
        (inventoryItem.stackQty ?? 0) / ingredient.qty
      );

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