import { api } from "./axiosInstance";
import type {
  CommitRecipesResult,
  GeneratedRecipeDraft,
  RecipeGeneratorConstraints,
  RecipeGeneratorSession,
} from "@/types/generator.types";

export async function createRecipeSession(constraints: RecipeGeneratorConstraints): Promise<RecipeGeneratorSession> {
  const { data } = await api.post<RecipeGeneratorSession>("/recipe-generator/sessions", constraints);
  return data;
}

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

export async function generateRecipeDrafts(sessionId: number, count = 3): Promise<RecipeGeneratorSession> {
  const { data } = await api.post<RecipeGeneratorSession>(`/recipe-generator/sessions/${sessionId}/generate`, {
    count,
  });
  return data;
}

export async function regenerateRecipePart(
  sessionId: number,
  draftId: string,
  mode: "ingredients" | "steps" | "full",
  instruction?: string,
): Promise<RecipeGeneratorSession> {
  const { data } = await api.post<RecipeGeneratorSession>(`/recipe-generator/sessions/${sessionId}/regenerate`, {
    draftId,
    mode,
    instruction,
  });
  return data;
}

export async function removeRecipeDraft(sessionId: number, draftId: string): Promise<RecipeGeneratorSession> {
  const { data } = await api.delete<RecipeGeneratorSession>(
    `/recipe-generator/sessions/${sessionId}/drafts/${encodeURIComponent(draftId)}`,
  );
  return data;
}

export async function updateRecipeDraft(
  sessionId: number,
  draft: GeneratedRecipeDraft,
): Promise<RecipeGeneratorSession> {
  const { data } = await api.put<RecipeGeneratorSession>(`/recipe-generator/sessions/${sessionId}/draft`, draft);
  return data;
}

export async function commitRecipes(sessionId: number, draftIds?: string[]): Promise<CommitRecipesResult> {
  const { data } = await api.post<CommitRecipesResult>(`/recipe-generator/sessions/${sessionId}/commit`, {
    draftIds: draftIds?.length ? draftIds : undefined,
  });
  return data;
}
