import { apiClient } from "./client";
import { API_ENDPOINTS } from "../config/api";

/**
 * Nutrition data types
 */
export interface NutritionEntry {
  id?: string;
  date: string; // YYYY-MM-DD
  totalCalories: number;
  calorieGoal: number;
  meals?: Array<{
    type: "breakfast" | "lunch" | "dinner" | "snack";
    name: string;
    calories: number;
    time?: string;
  }>;
  createdAt?: string;
  updatedAt?: string;
}

export interface MealEntry {
  id?: string;
  dailyNutritionId?: string;
  mealType: "breakfast" | "lunch" | "dinner" | "snack";
  foodName: string;
  calories: number;
  protein?: number;
  carbs?: number;
  fats?: number;
  timestamp?: string;
  createdAt?: string;
}

/**
 * Save or update daily nutrition
 */
export async function saveDailyNutrition(
  data: {
    date: string;
    totalCalories?: number;
    calorieGoal?: number;
    meals?: NutritionEntry["meals"];
  },
  token?: string | null,
): Promise<NutritionEntry> {
  const response = await apiClient.post<{
    success: boolean;
    data: { nutrition: NutritionEntry };
  }>(API_ENDPOINTS.NUTRITION.BASE, data, {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  });
  return response.data.data.nutrition;
}

/**
 * Get nutrition for a specific date
 */
export async function getNutritionByDate(
  date: string,
  token?: string | null,
): Promise<NutritionEntry | null> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      data: NutritionEntry | null;
    }>(API_ENDPOINTS.NUTRITION.GET_BY_DATE(date), {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
    });
    return response.data.data;
  } catch (error: any) {
    if (error.response?.status === 404) {
      return null;
    }
    throw error;
  }
}

/**
 * Get nutrition for a date range
 */
export async function getNutritionByRange(
  startDate: string,
  endDate: string,
  token?: string | null,
): Promise<NutritionEntry[]> {
  const response = await apiClient.get<{
    success: boolean;
    data: NutritionEntry[];
  }>(API_ENDPOINTS.NUTRITION.GET_RANGE(startDate, endDate), {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  });
  return response.data.data || [];
}

/**
 * Add a meal entry
 */
export async function addMealEntry(
  data: {
    mealType: MealEntry["mealType"];
    foodName: string;
    calories: number;
    protein?: number;
    carbs?: number;
    fats?: number;
    dailyNutritionId?: string;
  },
  token?: string | null,
): Promise<MealEntry> {
  const response = await apiClient.post<{
    success: boolean;
    data: MealEntry;
  }>(API_ENDPOINTS.NUTRITION.MEALS, data, {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  });
  return response.data.data;
}

/**
 * Get meal entries for a specific date
 */
export async function getMealEntriesByDate(
  date: string,
  token?: string | null,
): Promise<MealEntry[]> {
  const response = await apiClient.get<{
    success: boolean;
    data: MealEntry[];
  }>(`${API_ENDPOINTS.NUTRITION.MEALS}?date=${date}`, {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  });
  return response.data.data || [];
}

/**
 * Delete a meal entry
 */
export async function deleteMealEntry(
  id: string,
  token?: string | null,
): Promise<void> {
  await apiClient.delete(`${API_ENDPOINTS.NUTRITION.MEALS}?id=${id}`, {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  });
}
