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

/**
 * Hydration data types
 */
export interface HydrationEntry {
  id?: string;
  date: string; // YYYY-MM-DD
  totalWater: number; // ml
  waterGoal: number; // ml
  entries?: Array<{
    amount: number; // ml
    time: string;
  }>;
  createdAt?: string;
  updatedAt?: string;
}

/**
 * Save or update daily hydration
 */
export async function saveDailyHydration(
  data: {
    date: string;
    totalWater?: number;
    waterGoal?: number;
    entries?: HydrationEntry["entries"];
  },
  token?: string | null,
): Promise<HydrationEntry> {
  const response = await apiClient.post<{
    success: boolean;
    data: { hydration: HydrationEntry };
  }>(API_ENDPOINTS.HYDRATION.BASE, data, {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  });
  return response.data.data.hydration;
}

/**
 * Get hydration for a specific date
 */
export async function getHydrationByDate(
  date: string,
  token?: string | null,
): Promise<HydrationEntry | null> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      data: HydrationEntry | null;
    }>(API_ENDPOINTS.HYDRATION.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 hydration for a date range
 */
export async function getHydrationByRange(
  startDate: string,
  endDate: string,
  token?: string | null,
): Promise<HydrationEntry[]> {
  const response = await apiClient.get<{
    success: boolean;
    data: HydrationEntry[];
  }>(API_ENDPOINTS.HYDRATION.GET_RANGE(startDate, endDate), {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  });
  return response.data.data || [];
}
