import { Injectable } from '@angular/core';
import { UserGender } from 'src/app/core/interfaces/user.interface';
import { MealsByDate } from '../../interfaces/services/api-fit/response/meal.interface';
import { ApiFitService } from '../api-fit/api-fit.service';

@Injectable({
  providedIn: 'root',
})
export class UserService {
  constructor(private apiFitService: ApiFitService) {}
  TMB_FORMULAS = {
    female: (weight: number, heightInCentimeters: number, age: number) =>
      655.1 + 9.56 * weight + 1.85 * heightInCentimeters - 4.68 * age,
    male: (weight: number, heightInCentimeters: number, age: number) =>
      66.47 + 13.75 * weight + 5 * heightInCentimeters - 6.76 * age,
  };

  calculateTMB(
    gender: UserGender,
    weight: number,
    heightInCentimeters: number,
    age: number
  ): number {
    const tmb = this.TMB_FORMULAS[gender]?.(weight, heightInCentimeters, age);
    return tmb ?? 0;
  }

  calculateGET(tmb: number, multiplier: number): number {
    return tmb * multiplier;
  }

  calculateRecommendedRate(get: number, offset: number) {
    return get + offset ?? 0;
  }

  calculateAge(date: Date) {
    const today = new Date();
    const birthDate = new Date(date);

    if (!date || !birthDate) return;

    let age = today.getFullYear() - birthDate.getFullYear();
    const month = today.getMonth() - birthDate.getMonth();

    if (month < 0 || (month === 0 && today.getDate() < birthDate.getDate())) {
      age--;
    }

    return age;
  }

  fetchMealsByWeek(mealDate: Date) {
    return new Promise(
      (
        resolve: (mealsByWeek: MealsByDate[]) => void,
        reject: (err: unknown) => void
      ) => {
        this.apiFitService
          .getMealsByWeek({
            date: mealDate.toLocaleDateString('en-CA'),
          })
          .subscribe({
            next: (res) => resolve(res.data),
            error: reject,
          });
      }
    );
  }
}
