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

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

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

  const neededIngredientsPromises = data.neededIngredients?.map(async (i: ItemNeededIngredient) => {
    return await payload.findByID({
      collection: 'ingredients',
      id: i.ingredient as number || 0,
      select: {
        calories: true,
        protein: true,
        carbohydrates: true,
        fat: true,
        canBeGlutenFree: true,
        canBeHalal: true,
        canBeKosher: true,
        canBeVegan: true,
        canBeVegetarian: true,
      },
    })
  }) || []

  const ingredients = await Promise.all(neededIngredientsPromises)

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

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