import { Meal } from "@/payload-types"
type ItemNeeded = Extract<Meal['items'], Array<unknown>>[0]
import { BeforeChangeHook } from "node_modules/payload/dist/collections/config/types"

export const setMealNutritionOnChange: BeforeChangeHook = async (args) => {
  const data = args.data as Partial<Meal>
  const payload = args.req.payload

  if (!data.items?.length) {
    const zeroedOutNutrition: Partial<Meal> = {
      calories: 0,
      carbohydrates: 0,
      fat: 0,
      protein: 0,
      canBeKosher: false,
      canBeHalal: false,
      canBeVegan: false,
      canBeVegetarian: false,
      canBeGlutenFree: false,
    }
    return { ...data, ...zeroedOutNutrition }
  }

  const itemsPromises = data.items?.map(async (i: ItemNeeded) => {
    return await payload.findByID({
      collection: 'mealItems',
      id: i.item as number || 0,
      select: {
        calories: true,
        protein: true,
        carbohydrates: true,
        fat: true,
        canBeGlutenFree: true,
        canBeHalal: true,
        canBeKosher: true,
        canBeVegan: true,
        canBeVegetarian: true,
      },
    })
  }) || []

  const items = await Promise.all(itemsPromises)

  const updatedNutrition: Partial<Meal> = {
    calories: items.reduce((previousValue, item) => {
      const quantity = data.items?.find(i => i.item === item.id)?.quantity || 1
      return previousValue + ((item?.calories || 0) * quantity)
    }, 0),
    carbohydrates: items.reduce((previousValue, item) => {
      const quantity = data.items?.find(i => i.item === item.id)?.quantity || 1
      return previousValue + ((item?.carbohydrates || 0) * quantity)
    }, 0),
    fat: items.reduce((previousValue, item) => {
      const quantity = data.items?.find(i => i.item === item.id)?.quantity || 1
      return previousValue + ((item?.fat || 0) * quantity)
    }, 0),
    protein: items.reduce((previousValue, item) => {
      const quantity = data.items?.find(i => i.item === item.id)?.quantity || 1
      return previousValue + ((item?.protein || 0) * quantity)
    }, 0),
    canBeKosher: !items.find(i => !i.canBeKosher),
    canBeHalal: !items.find(i => !i.canBeHalal),
    canBeVegan: !items.find(i => !i.canBeVegan),
    canBeVegetarian: !items.find(i => !i.canBeVegetarian),
    canBeGlutenFree: !items.find(i => !i.canBeGlutenFree),
  }

  return { ...data, ...updatedNutrition }
}
