import { apiFetch } from '@/src/api/client';
import type {
  IngredientCategory,
  IngredientNutritionItem,
  UpsertIngredientNutritionItemInput,
} from '@/src/types/ingredient-catalog';

export async function fetchIngredientCategories(): Promise<IngredientCategory[]> {
  return apiFetch<IngredientCategory[]>('/ingredient-catalog/categories');
}

export async function fetchIngredientCatalogItems(params?: {
  category?: string;
  search?: string;
}): Promise<IngredientNutritionItem[]> {
  const query = new URLSearchParams();
  if (params?.category) query.set('category', params.category);
  if (params?.search) query.set('search', params.search);
  const suffix = query.toString() ? `?${query.toString()}` : '';
  return apiFetch<IngredientNutritionItem[]>(`/ingredient-catalog${suffix}`);
}

export async function createIngredientCatalogItem(
  input: UpsertIngredientNutritionItemInput,
): Promise<IngredientNutritionItem> {
  return apiFetch<IngredientNutritionItem>('/ingredient-catalog', {
    method: 'POST',
    body: JSON.stringify(input),
  });
}

export async function updateIngredientCatalogItem(
  id: number,
  input: UpsertIngredientNutritionItemInput,
): Promise<IngredientNutritionItem> {
  return apiFetch<IngredientNutritionItem>(`/ingredient-catalog/${id}`, {
    method: 'PUT',
    body: JSON.stringify(input),
  });
}

export async function deleteIngredientCatalogItem(id: number): Promise<void> {
  await apiFetch<void>(`/ingredient-catalog/${id}`, { method: 'DELETE' });
}
