import { useQuery, useMutation } from "@tanstack/react-query";
import { useBackdropStore } from "../context/zustand-store/appStore";
import api from "./axios";
import { AxiosError } from "axios";

type RequestParams = {
  api: string;
  method?: "get" | "post" | "put" | "delete" | "patch";
  params?: any;
  queryKey?: any[];
  enabled?: boolean;
  disableBackdrop?: boolean;
};

export function useApiRequest<TData = any>({
  api: url,
  params,
  queryKey = [url],
  enabled = true,
  disableBackdrop = false,
}: RequestParams) {
  const { openBackdrop, closeBackdrop } = useBackdropStore();

  return useQuery<TData>({
    queryKey,
    queryFn: async () => {
      if (!disableBackdrop && window.location.pathname !== "/") openBackdrop();

      try {
        const response = await api.get(url, { params });
        return response.data;
      } finally {
        if (!disableBackdrop) closeBackdrop();
      }
    },
    enabled,
    retry: 3,
  });
}

export function useApiMutation<TData = any>({
  api: url,
  method = "post",
  disableBackdrop = false,
}: RequestParams) {
  const { openBackdrop, closeBackdrop } = useBackdropStore();

  return useMutation<TData, AxiosError, any>({
    mutationFn: async (params) => {
      if (!disableBackdrop) openBackdrop();

      try {
        const response = await api.request({
          url,
          method,
          data: ["post", "put", "patch"].includes(method) ? params : undefined,
          params: ["get", "delete"].includes(method) ? params : undefined,
        });
        return response.data;
      } finally {
        if (!disableBackdrop) closeBackdrop();
      }
    },
  });
}
