import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as api from "../service/ProductService";
import type {
  CreateCategoryType,
  CreateProductType,
  GetProductsParams,
} from "../types/Types";
import type { FilterValues } from "@/components/Filters";

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

export const useGetProducts = (
  params?: GetProductsParams,
  filters?: FilterValues,
) => {
  return useQuery({
    queryKey: ["products", params, filters],
    queryFn: () => api.getProducts(params, filters),
  });
};

export const useGetProductDetails = (id: string) => {
  return useQuery({
    queryKey: ["product", id],
    queryFn: () => api.getProductDetails(id),
  });
};

export const useUpdateProduct = () => {
  return useMutation({
    mutationFn: ({ id, params }: { id: string; params: CreateProductType }) =>
      api.updateProduct(id, params),
  });
};

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

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

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"] });
    },
  });
};

export const useGetIcons = () => {
  return useQuery({
    queryKey: ["icons"],
    queryFn: api.getIcons,
  });
};
