import { Fraction } from '../../../shared/interfaces/fraction.interface';
import { NutrientQuantityToCalculate } from '../../../shared/interfaces/nutrients/nutrient-quantity-to-calculate.dto';

export function sumNutrientsQuantity(
  quantitiesToCalculate: NutrientQuantityToCalculate[],
  unit?: string,
) {
  let approximation = false;

  if (unit === 'percents') {
    const initialValue: Fraction = { denominator: 0, numerator: 0 };

    const fraction: Fraction = quantitiesToCalculate.reduce(
      (accumulator: Fraction, { nutrientQuantity, foodQuantity, unit }) => {
        if (!unit) {
          approximation = true;
          accumulator.denominator += foodQuantity;
          return accumulator;
        }

        nutrientQuantity = Number(nutrientQuantity);

        if (Number.isNaN(nutrientQuantity)) {
          approximation = true;
          accumulator.denominator += foodQuantity;
          return accumulator;
        }

        accumulator.denominator += foodQuantity;
        accumulator.numerator += (nutrientQuantity * foodQuantity) / 100;

        return accumulator;
      },
      initialValue,
    );

    const quantity = Math.round(
      (fraction.numerator / fraction.denominator) * 100,
    );

    return { quantity, approximation };
  }

  const quantity = quantitiesToCalculate.reduce(
    (accumulator: number, { nutrientQuantity, foodQuantity, unit }) => {
      if (!unit) {
        approximation = true;
        return accumulator;
      }

      nutrientQuantity = Number(nutrientQuantity);

      if (Number.isNaN(nutrientQuantity)) {
        approximation = true;
        return accumulator;
      }

      return accumulator + (nutrientQuantity * foodQuantity) / 100;
    },
    0,
  );

  const roundedQuantity = Math.round(quantity);

  return { quantity: roundedQuantity, approximation };
}
