import { apiClient } from "./client";
import { API_ENDPOINTS } from "../config/api";
import { getErrorMessage } from "../utils/error-helpers";
import log from "../utils/logger";

export interface FitnessProfile {
  id?: string;
  userId: string;
  height?: number;
  weight?: number;
  age?: number;
  gender?: "male" | "female" | "other" | "prefer_not_to_say";
  fitnessGoals?: string[];
  activityLevel?:
    | "sedentary"
    | "lightly_active"
    | "moderately_active"
    | "very_active"
    | "extremely_active";
  medicalConditions?: string;
  allergies?: string;
  injuries?: string;
  preferences?: string;
}

export const fitnessProfileApi = {
  getFitnessProfile: async (token: string): Promise<FitnessProfile | null> => {
    try {
      log.debug("Getting fitness profile");
      const response = await apiClient.get(`${API_ENDPOINTS.PROFILE.FITNESS}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      return response.data.profile || null;
    } catch (error: unknown) {
      log.error("Failed to fetch fitness profile", error);
      throw error;
    }
  },

  checkProfileExists: async (token: string): Promise<boolean> => {
    try {
      const profile = await fitnessProfileApi.getFitnessProfile(token);
      return profile !== null;
    } catch (error: unknown) {
      log.error("Failed to check if fitness profile exists", error);
      return false;
    }
  },

  updateFitnessProfile: async (
    data: Partial<FitnessProfile>,
    token: string,
  ): Promise<FitnessProfile> => {
    try {
      const response = await apiClient.put(
        `${API_ENDPOINTS.PROFILE.FITNESS}`,
        data,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );
      return response.data;
    } catch (error: unknown) {
      log.error("Failed to update fitness profile", error);
      throw error;
    }
  },

  createFitnessProfile: async (
    data: Omit<FitnessProfile, "id">,
    token: string,
  ): Promise<FitnessProfile> => {
    try {
      const response = await apiClient.post(
        `${API_ENDPOINTS.PROFILE.FITNESS}`,
        data,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );
      return response.data;
    } catch (error: unknown) {
      log.error("Failed to create fitness profile", error);
      throw error;
    }
  },
};
