import { api } from "./axiosInstance";
import type {
  CommitDietPlanResult,
  DietGeneratorSession,
  DietUserProfile,
  MacroProposal,
} from "@/types/generator.types";

export async function fetchDietProfile(): Promise<DietUserProfile | null> {
  const { data } = await api.get<DietUserProfile>("/diet-generator/profile");
  return data.heightCm ? data : null;
}

export async function saveDietProfile(profile: DietUserProfile): Promise<DietUserProfile> {
  const { data } = await api.put<DietUserProfile>("/diet-generator/profile", profile);
  return data;
}

export async function createDietSession(input: {
  planStartDate?: string;
  planDayCount?: number;
  calorieToleranceKcal?: number;
}): Promise<DietGeneratorSession> {
  const { data } = await api.post<DietGeneratorSession>("/diet-generator/sessions", input);
  return data;
}

export async function fetchDietSession(id: number): Promise<DietGeneratorSession> {
  const { data } = await api.get<DietGeneratorSession>(`/diet-generator/sessions/${id}`);
  return data;
}

export async function proposeDietMacros(sessionId: number): Promise<DietGeneratorSession> {
  const { data } = await api.post<DietGeneratorSession>(`/diet-generator/sessions/${sessionId}/propose-macros`);
  return data;
}

export async function acceptDietMacros(
  sessionId: number,
  macros?: Partial<MacroProposal>,
): Promise<DietGeneratorSession> {
  const { data } = await api.post<DietGeneratorSession>(`/diet-generator/sessions/${sessionId}/accept-macros`, {
    calories: macros?.calories,
    proteinG: macros?.proteinG,
    fatG: macros?.fatG,
    carbsG: macros?.carbsG,
  });
  return data;
}

export async function generateDietPlan(sessionId: number): Promise<DietGeneratorSession> {
  const { data } = await api.post<DietGeneratorSession>(`/diet-generator/sessions/${sessionId}/generate-plan`);
  return data;
}

export async function regenerateDietMeal(
  sessionId: number,
  planDate: string,
  mealCategory: number,
): Promise<DietGeneratorSession> {
  const { data } = await api.post<DietGeneratorSession>(`/diet-generator/sessions/${sessionId}/regenerate-meal`, {
    planDate,
    mealCategory,
  });
  return data;
}

export async function toggleDietMealLock(
  sessionId: number,
  mealId: number,
  isLocked: boolean,
): Promise<DietGeneratorSession> {
  const { data } = await api.patch<DietGeneratorSession>(`/diet-generator/sessions/${sessionId}/meals/${mealId}`, {
    isLocked,
  });
  return data;
}

export async function commitDietPlan(sessionId: number): Promise<CommitDietPlanResult> {
  const { data } = await api.post<CommitDietPlanResult>(`/diet-generator/sessions/${sessionId}/commit`);
  return data;
}
