import type { DailyTargets, NutritionValues } from "@app/shared-types";
import { roundNutrition, sumNutrition } from "./calc.js";

export interface DaySummary {
  consumed: NutritionValues;
  targets: DailyTargets;
  remaining: {
    kcal: number;
    proteinG: number;
    carbsG: number;
    fatG: number;
    fiberG: number;
  };
  /** Andel av dagsmålet (0–1+), för progressvisning. */
  progress: {
    kcal: number;
    proteinG: number;
    carbsG: number;
    fatG: number;
    fiberG: number;
    saltOfMax: number;
  };
  saltWarning: boolean;
}

/** "Min dag" (spec §4.3): summera loggade måltider mot dagsmål. */
export function summarizeDay(meals: NutritionValues[], targets: DailyTargets): DaySummary {
  const consumed = roundNutrition(sumNutrition(meals));
  const remaining = {
    kcal: Math.round(targets.kcal - consumed.kcal),
    proteinG: Math.round((targets.proteinG - consumed.proteinG) * 10) / 10,
    carbsG: Math.round((targets.carbsG - consumed.carbsG) * 10) / 10,
    fatG: Math.round((targets.fatG - consumed.fatG) * 10) / 10,
    fiberG: Math.round((targets.fiberG - consumed.fiberG) * 10) / 10,
  };
  const safeDiv = (a: number, b: number) => (b > 0 ? a / b : 0);
  return {
    consumed,
    targets,
    remaining,
    progress: {
      kcal: safeDiv(consumed.kcal, targets.kcal),
      proteinG: safeDiv(consumed.proteinG, targets.proteinG),
      carbsG: safeDiv(consumed.carbsG, targets.carbsG),
      fatG: safeDiv(consumed.fatG, targets.fatG),
      fiberG: safeDiv(consumed.fiberG, targets.fiberG),
      saltOfMax: safeDiv(consumed.saltG, targets.saltMaxG),
    },
    saltWarning: consumed.saltG > targets.saltMaxG,
  };
}
