import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { QUERY_KEYS } from "@/utils/query-key";
import toast from "react-hot-toast";
import {
  getOrders,
  getOrder,
  updateOrderStatus,
  getOrderStats,
} from "./_requests";
import { OrderFilters, UpdateOrderStatusRequest } from "./_models";

export const useOrders = (filters?: OrderFilters) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_ORDERS, filters],
    queryFn: () => getOrders(filters),
  });
};

export const useOrder = (id: string) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_ORDER, id],
    queryFn: () => getOrder(id),
    enabled: !!id,
  });
};

export const useOrderStats = (enabled: boolean = true) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_ORDERS, "stats"],
    queryFn: getOrderStats,
    enabled,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
};

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

  return useMutation({
    mutationFn: ({
      id,
      payload,
    }: {
      id: string;
      payload: UpdateOrderStatusRequest;
    }) => updateOrderStatus(id, payload),
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_ORDERS],
      });
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_ORDER, variables.id],
      });
      toast.success("وضعیت سفارش با موفقیت به‌روزرسانی شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در به‌روزرسانی وضعیت سفارش");
    },
  });
};
