import { apiFetch } from '@/src/api/client';
import type {
  CommitRecipesResult,
  GeneratedRecipeDraft,
  RecipeGeneratorConstraints,
  RecipeGeneratorSession,
} from '@/src/types/generator';

export async function createRecipeSession(
  constraints: RecipeGeneratorConstraints,
): Promise<RecipeGeneratorSession> {
  return apiFetch<RecipeGeneratorSession>('/api/recipe-generator/sessions', {
    method: 'POST',
    body: constraints,
  });
}

export async function generateRecipeDrafts(sessionId: number, count = 3): Promise<RecipeGeneratorSession> {
  return apiFetch<RecipeGeneratorSession>(`/api/recipe-generator/sessions/${sessionId}/generate`, {
    method: 'POST',
    body: { count },
  });
}

export async function regenerateRecipePart(
  sessionId: number,
  draftId: string,
  mode: 'ingredients' | 'steps' | 'full',
  instruction?: string,
): Promise<RecipeGeneratorSession> {
  return apiFetch<RecipeGeneratorSession>(`/api/recipe-generator/sessions/${sessionId}/regenerate`, {
    method: 'POST',
    body: { draftId, mode, instruction },
  });
}

export async function removeRecipeDraft(sessionId: number, draftId: string): Promise<RecipeGeneratorSession> {
  return apiFetch<RecipeGeneratorSession>(
    `/api/recipe-generator/sessions/${sessionId}/drafts/${encodeURIComponent(draftId)}`,
    { method: 'DELETE' },
  );
}

export async function commitRecipes(sessionId: number, draftIds?: string[]): Promise<CommitRecipesResult> {
  return apiFetch<CommitRecipesResult>(`/api/recipe-generator/sessions/${sessionId}/commit`, {
    method: 'POST',
    body: { draftIds: draftIds?.length ? draftIds : undefined },
  });
}

export async function updateRecipeDraft(
  sessionId: number,
  draft: GeneratedRecipeDraft,
): Promise<RecipeGeneratorSession> {
  return apiFetch<RecipeGeneratorSession>(`/api/recipe-generator/sessions/${sessionId}/draft`, {
    method: 'PUT',
    body: draft,
  });
}
