import { apiFetch } from '@/src/api/client';
import type {
  CategoryCount,
  CreateRecipeInput,
  MealCategory,
  RecipeDetail,
  RecipeListItem,
} from '@/src/types/recipe';

export async function fetchRecipes(params?: {
  category?: MealCategory;
  search?: string;
  ingredient?: string;
}): Promise<RecipeListItem[]> {
  const query = new URLSearchParams();
  if (params?.category != null) query.set('category', String(params.category));
  if (params?.search) query.set('search', params.search);
  if (params?.ingredient) query.set('ingredient', params.ingredient);
  const qs = query.toString();
  return apiFetch<RecipeListItem[]>(`/recipes${qs ? `?${qs}` : ''}`);
}

export async function fetchRecipeById(id: number): Promise<RecipeDetail> {
  return apiFetch<RecipeDetail>(`/recipes/${id}`);
}

export async function fetchCategories(): Promise<CategoryCount[]> {
  return apiFetch<CategoryCount[]>('/recipes/categories');
}

export async function createRecipe(input: CreateRecipeInput): Promise<RecipeDetail> {
  return apiFetch<RecipeDetail>('/recipes', {
    method: 'POST',
    body: {
      name: input.name,
      mealCategory: input.mealCategory,
      calories: input.calories,
      protein: input.protein,
      fat: input.fat,
      carbs: input.carbs,
      prepTimeMinutes: input.prepTimeMinutes,
      ingredients: input.ingredients.map((i, index) => ({
        name: i.name,
        amountGrams: i.amountGrams,
        unit: i.unit.trim() || null,
        catalogItemId: i.catalogItemId ?? null,
        sortOrder: i.sortOrder || index,
      })),
      steps: input.steps,
    },
  });
}
