import { BadGatewayException } from '@nestjs/common';
import { IUser } from '../../decorators/auth/user.decorator';
import { EntityManager } from 'typeorm';
import { getAge } from './get-age.function';
import { BMR_Formulas } from './bmr-formulas.function';
import { TDEE_Formula } from './tdee-formula.funtion';

export async function retrieveUserTDEE(
  entityManager: EntityManager,
  userPayload: IUser,
): Promise<number | null> {
  const { id } = userPayload;

  const SQL = `
    SELECT
      person.weight AS weight,
      person.height AS height,
      person.birth_date AS birthDate,
      person.gender AS gender,
      goal.tdee_offset AS tdeeOffset,
      physical_activity.tdee_multiplier AS tdeeMultiplier
    FROM person
    INNER JOIN user
      ON person.id = user.person_id
    INNER JOIN physical_activity
      ON person.physical_activity_id = physical_activity.id
    INNER JOIN goal
      ON person.goal_id = goal.id
    WHERE person.id = ?
  `;

  const [user] = await entityManager.query(SQL, [id]).catch(() => {
    throw new BadGatewayException();
  });

  if (!user) return null;

  const age = getAge(user.birthDate);

  const heightInCentimeters = user.height * 100;

  const basalMetabolicRate = Math.round(
    BMR_Formulas[user.gender](user.weight, heightInCentimeters, age),
  );

  const totalDailyEnergyExpenditure = Math.round(
    TDEE_Formula(basalMetabolicRate, user.tdeeMultiplier, user.tdeeOffset),
  );

  return totalDailyEnergyExpenditure;
}
