import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as api from "../service/FoodService";
import type {
  CreateCategoryType,
  CreateFoodType,
  GetFoodsParams,
} from "../types/Types";

export const useCreateFood = () => {
  return useMutation({
    mutationFn: api.createFood,
  });
};

export const useGetFoods = (params?: GetFoodsParams) => {
  return useQuery({
    queryKey: ["foods", params],
    queryFn: () => api.getFoods(params),
  });
};

export const useGetFoodDetails = (id: string) => {
  return useQuery({
    queryKey: ["food", id],
    queryFn: () => api.getFoodDetails(id),
  });
};

export const useUpdateFood = () => {
  return useMutation({
    mutationFn: ({ id, params }: { id: string; params: CreateFoodType }) =>
      api.updateFood(id, params),
  });
};

export const useGetCategories = () => {
  return useQuery({
    queryKey: ["categories"],
    queryFn: api.getCategories,
  });
};

export const useDeleteFood = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.deleteFood,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["foods"] });
    },
  });
};

export const useCreateCategory = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.createCategory,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["categories"] });
    },
  });
};

export const useDeleteCategory = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.deleteCategory,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["categories"] });
    },
  });
};

export const useUpdateCategory = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, params }: { id: string; params: CreateCategoryType }) =>
      api.updateCategory(id, params),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["categories"] });
    },
  });
};
