import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { QUERY_KEYS } from "@/utils/query-key";
import toast from "react-hot-toast";
import {
  getShippingMethods,
  getShippingMethod,
  createShippingMethod,
  updateShippingMethod,
  deleteShippingMethod,
} from "./_requests";
import {
  CreateShippingMethodRequest,
  UpdateShippingMethodRequest,
} from "./_models";

export const useShippingMethods = () => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_SHIPPING_METHODS],
    queryFn: getShippingMethods,
  });
};

export const useShippingMethod = (id: string) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_SHIPPING_METHOD, id],
    queryFn: () => getShippingMethod(id),
    enabled: !!id,
  });
};

export const useCreateShippingMethod = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (payload: CreateShippingMethodRequest) =>
      createShippingMethod(payload),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_SHIPPING_METHODS],
      });
      toast.success("روش ارسال با موفقیت ایجاد شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در ایجاد روش ارسال");
    },
  });
};

export const useUpdateShippingMethod = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (payload: UpdateShippingMethodRequest) =>
      updateShippingMethod(payload.id.toString(), payload),
    onSuccess: (data: any) => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_SHIPPING_METHODS],
      });
      if (data?.id) {
        queryClient.invalidateQueries({
          queryKey: [QUERY_KEYS.GET_SHIPPING_METHOD, data.id.toString()],
        });
      }
      toast.success("روش ارسال با موفقیت به‌روزرسانی شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در به‌روزرسانی روش ارسال");
    },
  });
};

export const useDeleteShippingMethod = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => deleteShippingMethod(id),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_SHIPPING_METHODS],
      });
      toast.success("روش ارسال با موفقیت حذف شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در حذف روش ارسال");
    },
  });
};
