import { apiFetch } from '@/src/api/client';
import type {
  CommitDietPlanResult,
  DietGeneratorSession,
  DietUserProfile,
  MacroProposal,
} from '@/src/types/generator';

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

export async function saveDietProfile(profile: DietUserProfile): Promise<DietUserProfile> {
  return apiFetch<DietUserProfile>('/api/diet-generator/profile', {
    method: 'PUT',
    body: profile,
  });
}

export async function createDietSession(input: {
  planStartDate?: string;
  planDayCount?: number;
  calorieToleranceKcal?: number;
}): Promise<DietGeneratorSession> {
  return apiFetch<DietGeneratorSession>('/api/diet-generator/sessions', {
    method: 'POST',
    body: input,
  });
}

export async function fetchDietSession(id: number): Promise<DietGeneratorSession> {
  return apiFetch<DietGeneratorSession>(`/api/diet-generator/sessions/${id}`);
}

export async function proposeDietMacros(sessionId: number): Promise<DietGeneratorSession> {
  return apiFetch<DietGeneratorSession>(`/api/diet-generator/sessions/${sessionId}/propose-macros`, {
    method: 'POST',
  });
}

export async function acceptDietMacros(
  sessionId: number,
  macros?: Partial<MacroProposal>,
): Promise<DietGeneratorSession> {
  return apiFetch<DietGeneratorSession>(`/api/diet-generator/sessions/${sessionId}/accept-macros`, {
    method: 'POST',
    body: {
      calories: macros?.calories,
      proteinG: macros?.proteinG,
      fatG: macros?.fatG,
      carbsG: macros?.carbsG,
    },
  });
}

export async function generateDietPlan(sessionId: number): Promise<DietGeneratorSession> {
  return apiFetch<DietGeneratorSession>(`/api/diet-generator/sessions/${sessionId}/generate-plan`, {
    method: 'POST',
  });
}

export async function regenerateDietMeal(
  sessionId: number,
  planDate: string,
  mealCategory: number,
): Promise<DietGeneratorSession> {
  return apiFetch<DietGeneratorSession>(`/api/diet-generator/sessions/${sessionId}/regenerate-meal`, {
    method: 'POST',
    body: { planDate, mealCategory },
  });
}

export async function toggleDietMealLock(
  sessionId: number,
  mealId: number,
  isLocked: boolean,
): Promise<DietGeneratorSession> {
  return apiFetch<DietGeneratorSession>(`/api/diet-generator/sessions/${sessionId}/meals/${mealId}`, {
    method: 'PATCH',
    body: { isLocked },
  });
}

export async function commitDietPlan(sessionId: number): Promise<CommitDietPlanResult> {
  return apiFetch<CommitDietPlanResult>(`/api/diet-generator/sessions/${sessionId}/commit`, {
    method: 'POST',
  });
}
