import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as api from "../service/OrderService";
import type { GetOrdersParams, ChangeOrderStatusParams, RefundPaymentParams } from "../service/OrderService";

export const useGetOrders = (params?: GetOrdersParams) => {
  return useQuery({
    queryKey: ["orders", params],
    queryFn: () => api.getOrders(params),
  });
};

export const useGetOrderById = (orderId: string) => {
  return useQuery({
    queryKey: ["order", orderId],
    queryFn: () => api.getOrderById(orderId),
    enabled: !!orderId,
  });
};

export const useConfirmOrder = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (orderId: string) => api.confirmOrder(orderId),
    onSuccess: (_, orderId) => {
      queryClient.invalidateQueries({ queryKey: ["order", orderId] });
      queryClient.invalidateQueries({ queryKey: ["orders"] });
    },
  });
};

export const useVerifyCashPayment = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (paymentId: string) => api.verifyCashPayment(paymentId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["order"] });
      queryClient.invalidateQueries({ queryKey: ["orders"] });
    },
  });
};

export const useChangeOrderStatus = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ orderId, status, params }: { orderId: string; status: string; params?: ChangeOrderStatusParams }) =>
      api.changeOrderStatus(orderId, status, params),
    onSuccess: (_, { orderId }) => {
      queryClient.invalidateQueries({ queryKey: ["order", orderId] });
      queryClient.invalidateQueries({ queryKey: ["orders"] });
    },
  });
};

export const useRefundPayment = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ orderId, params }: { orderId: string; params: RefundPaymentParams }) =>
      api.refundPayment(orderId, params),
    onSuccess: (_, { orderId }) => {
      queryClient.invalidateQueries({ queryKey: ["order", orderId] });
      queryClient.invalidateQueries({ queryKey: ["orders"] });
    },
  });
};
