import { NutrientPer100GramsDto } from '../../../shared/dtos/nutrients/nutrient-per-100-grams.dto';
import { NutrientDto } from '../../../shared/dtos/nutrients/nutrient.dto';

export function sortNutrients(
  nutrients: NutrientPer100GramsDto[] | NutrientDto[],
) {
  const unitsToGramsDivision = {
    g: 1,
    mg: 1000,
    mcg: 1000000,
    percents: null,
  };

  nutrients.sort((a: any, b: any) => {
    const aIsNaN = Number.isNaN(Number(a.quantityPer100 ?? a.quantity));

    const bIsNaN = Number.isNaN(Number(b.quantityPer100 ?? b.quantity));

    if (aIsNaN && bIsNaN) return 0;

    if (aIsNaN) return 1;

    if (bIsNaN) return -1;

    const quantityA = (a.quantityPer100 ?? a.quantity) as number;

    const quantityAInGrams = quantityA / unitsToGramsDivision[a.unit];

    const quantityB = (b.quantityPer100 ?? b.quantity) as number;

    const quantityBInGrams = quantityB / unitsToGramsDivision[b.unit];

    return quantityBInGrams - quantityAInGrams;
  });
}
