import {
  getItemKey,
  ShoppingCartItem,
  RewardSelectionItem,
} from '@isa/checkout/data-access';

/**
 * Merges items from regular shopping cart and reward shopping cart.
 * Items are grouped by EAN, destination, and orderItemType.
 * If an item exists in both carts with the same key, it will have both
 * cartQuantity and rewardCartQuantity.
 *
 * @param shoppingCartItems - Items from the regular shopping cart
 * @param rewardShoppingCartItems - Items from the reward shopping cart
 * @returns Merged array of reward selection items
 */
export const mergeRewardSelectionItems = (
  shoppingCartItems: ShoppingCartItem[],
  rewardShoppingCartItems: ShoppingCartItem[],
): RewardSelectionItem[] => {
  const itemsMap = new Map<string, RewardSelectionItem>();

  // Add items from regular shopping cart
  shoppingCartItems.forEach((shoppingCartItem) => {
    const key = getItemKey(shoppingCartItem);
    itemsMap.set(key, {
      item: shoppingCartItem,
      cartQuantity: shoppingCartItem.quantity ?? 0,
      rewardCartQuantity: 0,
      catalogPrice: undefined,
      availabilityPrice: undefined,
      catalogRewardPoints: undefined,
    });
  });

  // Merge items from reward shopping cart
  rewardShoppingCartItems.forEach((shoppingCartItem) => {
    const key = getItemKey(shoppingCartItem);
    const existingItem = itemsMap.get(key);

    if (existingItem) {
      // Item exists in both carts with same EAN, destination, and orderItemType - merge quantities
      itemsMap.set(key, {
        ...existingItem,
        rewardCartQuantity: shoppingCartItem.quantity ?? 0,
      });
    } else {
      // Item only in reward cart or different destination/orderItemType
      itemsMap.set(key, {
        item: shoppingCartItem,
        cartQuantity: 0,
        rewardCartQuantity: shoppingCartItem.quantity ?? 0,
        catalogPrice: undefined,
        availabilityPrice: undefined,
        catalogRewardPoints: undefined,
      });
    }
  });

  return Array.from(itemsMap.values());
};
