import merge from 'lodash/merge';
import toArray from 'lodash/toArray';
import { sortNutrients } from './sort-nutrients.function';
import { sumNutrientsQuantity } from './sum-nutrients-quantity.function';
import { NutrientWithQuantitiesToCalculate } from '../../../shared/interfaces/nutrients/nutrient-with-quantities-to-calculate.interface';
import { NutrientDto } from '../../../shared/dtos/nutrients/nutrient.dto';
import { NutrientQuantityToCalculate } from '../../../shared/interfaces/nutrients/nutrient-quantity-to-calculate.dto';
import { NutrientIntakesDto } from '../../dtos/nutrients/nutrient-intakes.dto';

export function mergeAndSumIntakesAndNutrientsQuantity(
  nutrients: NutrientWithQuantitiesToCalculate[],
  userTDEE?: number | null,
) {
  nutrients?.forEach((nutrient) => {
    const intakes: NutrientIntakesDto = {};

    if (userTDEE && nutrient.personalIntakes) {
      const { kcalPerGram, tdeePercentage } = nutrient.personalIntakes;

      intakes.personal = {
        quantity: Math.round((userTDEE * (tdeePercentage / 100)) / kcalPerGram),
        unit: 'g',
      };

      nutrient.intakes = intakes;
    }

    delete nutrient.personalIntakes;

    if (!intakes.personal && nutrient.intakes) {
      nutrient.intakes = merge(intakes, ...toArray(nutrient.intakes));
    }

    nutrient.unit =
      (nutrient.quantity as NutrientQuantityToCalculate[]).find(
        ({ unit }) => unit,
      )?.unit ?? null;

    const { quantity, approximation } = sumNutrientsQuantity(
      nutrient.quantity as NutrientQuantityToCalculate[],
      nutrient.unit,
    );

    nutrient.quantity =
      quantity !== 0 ? Math.round(quantity * 1000) / 1000 : '*';

    if (approximation && quantity !== 0) nutrient.quantity += '*';
  });

  sortNutrients(nutrients as NutrientDto[]);
}
