import { useQuery } from "@tanstack/react-query";
import * as recipesApi from "@/api/recipes.api";
import type { MealCategory } from "@/types/recipe.types";

const keys = {
  all: ["recipes"] as const,
  list: (category?: MealCategory, search?: string, ingredient?: string) =>
    [...keys.all, "list", category ?? "all", search ?? "", ingredient ?? ""] as const,
  detail: (id: number) => [...keys.all, "detail", id] as const,
  categories: () => [...keys.all, "categories"] as const,
};

export function useRecipes(category?: MealCategory, search?: string, ingredient?: string) {
  return useQuery({
    queryKey: keys.list(category, search, ingredient),
    queryFn: () => recipesApi.fetchRecipes({ category, search, ingredient }),
  });
}

export function useRecipe(id: number) {
  return useQuery({
    queryKey: keys.detail(id),
    queryFn: () => recipesApi.fetchRecipeById(id),
    enabled: Number.isFinite(id) && id > 0,
  });
}

export function useCategories() {
  return useQuery({
    queryKey: keys.categories(),
    queryFn: recipesApi.fetchCategories,
  });
}
