import { IItemContainer } from "@rpg-engine/shared";

export const countItemFromInventory = (itemKey: string, inventory: IItemContainer): number => {
  let totalQty = 0;

  if (!inventory) {
    return totalQty;
  }

  Object.keys(inventory.slots).forEach(i => {
    const index = parseInt(i);
    const item = inventory.slots[index];

    if (!item) {
      return;
    }

    // Count matching items
    if (item.key === itemKey) {
      totalQty += item.stackQty || 1;
    }

    // Recursively check nested containers
    if (item.isItemContainer && item.itemContainer && typeof item.itemContainer !== "string") {
      totalQty += countItemFromInventory(itemKey, item.itemContainer);
    }
  });

  return totalQty;
};