import { useMutation, useQuery } from '@tanstack/react-query';
import * as api from "../service/ProductService";
import {
  type CreateProductDetailRequestType,
  type CreateProductAttributeRequestType,
  type SaveProductRequestType,
  type UpdateVariantRequestType,
  type UpdateProductDetailRequestType,
  type UpdateProductAttributeRequestType,
  type UpdateProductRequestType
} from "../types/Types";

export const useCreateProductDetail = () => {
  return useMutation({
    mutationFn: (variables: CreateProductDetailRequestType) => api.createProductDetail(variables),
  });
};

export const useCreateProductAttribute = () => {
  return useMutation({
    mutationFn: (variables: CreateProductAttributeRequestType) => api.createProductAttribute(variables),
  });
};

export const useSaveProduct = () => {
  return useMutation({
    mutationFn: (variables: SaveProductRequestType) => api.saveProduct(variables),
  });
};

export const useGetProducts = (page: number = 1, limit: number = 10) => {
  return useQuery({
    queryKey: ['products', page, limit],
    queryFn: () => api.getProducts(page, limit),
  });
};

export const useGetProductVariants = (productId: string) => {
  return useQuery({
    queryKey: ['product-variants', productId],
    queryFn: () => api.getProductVariants(productId),
    enabled: !!productId,
  });
};

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

export const useGetProductById = (id: string) => {
  return useQuery({
    queryKey: ['product-by-id', id],
    queryFn: () => api.getProductById(id),
    enabled: !!id,
  });
};

export const useUpdateVariant = () => {
  return useMutation({
    mutationFn: (variables: UpdateVariantRequestType) => api.updateVariant(variables),
  });
};

export const useGetVariantById = (productId: string, variantId: string) => {
  return useQuery({
    queryKey: ['variant-by-id', productId, variantId],
    queryFn: () => api.getVariantById(productId, variantId),
    enabled: !!productId && !!variantId,
  });
};

export const useUpdateProductDetail = () => {
  return useMutation({
    mutationFn: (variables: UpdateProductDetailRequestType) => api.updateProductDetail(variables),
  });
};

export const useUpdateProductAttribute = () => {
  return useMutation({
    mutationFn: (variables: UpdateProductAttributeRequestType) => api.updateProductAttribute(variables),
  });
};

export const useUpdateProduct = () => {
  return useMutation({
    mutationFn: (variables: UpdateProductRequestType) => api.updateProduct(variables),
  });
};

export const useSearchProducts = (search: string, enabled: boolean = true) => {
  return useQuery({
    queryKey: ['products-search', search],
    queryFn: () => api.getProducts(1, 50, search),
    enabled: enabled,
  });
};