import { useSharedStore } from "@/share/store/sharedStore";
import * as api from "../service/Service";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";

export const useGetCart = () => {
  const { isLogin } = useSharedStore();

  return useQuery({
    queryKey: ["cart"],
    queryFn: api.getCart,
    enabled: isLogin,
  });
};

export const useAddToCart = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: api.addToCart,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["cart"] });
    },
  });
};

export const useUpdateCart = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: api.updateCart,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["cart"] });
    },
  });
};

export const useRemoveFromCart = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: api.removeFromCart,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["cart"] });
    },
  });
};

export const useShippingCost = () => {
  return useQuery({
    queryKey: ["shipping-cost"],
    queryFn: api.shippingCost,
  });
};

export const usePaymentMethods = () => {
  return useQuery({
    queryKey: ["payment-methods"],
    queryFn: api.paymentMethods,
  });
};

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

export const useApplyDiscountCode = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: api.applyDiscountCode,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["cart"] });
    },
  });
};

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

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

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

export const useGetShipmentCart = () => {
  return useQuery({
    queryKey: ["shipment-cart"],
    queryFn: api.getShipmentCart,
  });
};

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