import type { CartItem } from '../types/Types';
import type { Food } from '@/app/[name]/(Main)/types/Types';

export function cartItemToFood(item: CartItem, menuFood?: Food): Food {
  if (menuFood) {
    return menuFood;
  }

  return {
    id: item.foodId,
    category: '',
    title: item.foodTitle,
    desc: '',
    content: [],
    price: item.price,
    prepareTime: 0,
    isActive: true,
    images: [],
    inPlaceServe: true,
    pickupServe: true,
    discount: item.discount,
    isSpecialOffer: false,
    isAvailable: true,
    unavailabilityMessage: null,
  };
}

export function cartItemsToFoods(items: CartItem[], foods: Food[]): Food[] {
  return items
    .filter((item) => item.quantity > 0)
    .map((item) => {
      const menuFood = foods.find(
        (food) => String(food.id) === String(item.foodId)
      );
      return cartItemToFood(item, menuFood);
    });
}

export function guestCartItemsToFoods(
  items: Record<string | number, { quantity: number }>,
  foods: Food[]
): Food[] {
  return Object.entries(items)
    .filter(([, detail]) => detail?.quantity && detail.quantity > 0)
    .map(([id]) => foods.find((food) => String(food.id) === String(id)))
    .filter((food): food is Food => Boolean(food));
}

export function hasCartEntries(
  items: Record<string | number, { quantity: number }>
): boolean {
  return Object.values(items).some((detail) => detail?.quantity && detail.quantity > 0);
}
