import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  getPaymentMethod,
  getShipmentMethod,
  setAddressCart,
  setDeliveryMethod,
  setPaymentMethod,
  createOrder,
  applyCoupon,
  removeCoupon,
  setTableNumber,
  getOrderDetail,
  cancelOrder,
  confirmOrder,
} from "../service/OrderService";

export const useGetShipmentMethod = () => {
  return useQuery({
    queryKey: ["shipment-method"],
    queryFn: getShipmentMethod,
  });
};

export const useGetPaymentMethod = () => {
  return useQuery({
    queryKey: ["payment-method"],
    queryFn: getPaymentMethod,
  });
};

export const useSetAddressCart = () => {
  return useMutation({
    mutationFn: setAddressCart,
  });
};

export const useSetDeliveryMethod = () => {
  return useMutation({
    mutationFn: setDeliveryMethod,
  });
};

export const useSetPaymentMethod = () => {
  return useMutation({
    mutationFn: setPaymentMethod,
  });
};

export const useCreateOrder = () => {
  return useMutation({
    mutationFn: createOrder,
  });
};

export const useApplyCoupon = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: applyCoupon,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["cart-items"] });
      queryClient.invalidateQueries({ queryKey: ["cart-total"] });
    },
  });
};

export const useRemoveCoupon = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: removeCoupon,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["cart-items"] });
      queryClient.invalidateQueries({ queryKey: ["cart-total"] });
    },
  });
};

export const useSetTableNumber = () => {
  return useMutation({
    mutationFn: setTableNumber,
  });
};

export const useGetOrderDetail = (id: string) => {
  return useQuery({
    queryKey: ["order-detail", id],
    queryFn: () => getOrderDetail(id),
    enabled: !!id,
  });
};

export const useCancelOrder = () => {
  return useMutation({
    mutationFn: cancelOrder,
  });
};

export const useConfirmOrder = () => {
  return useMutation({
    mutationFn: confirmOrder,
  });
};
