import { useQuery } from "react-query";
import useAxios from "./useAxios";
import { useLocation, useNavigate } from "react-router-dom";
import useAuthState from "../../lib/state mangment/AuthState";
import { PaginationParams } from "../utils/PaginationParams";

function useGetQueryPagination(
  KEY: string | string[],
  url: string,
  params: any = {},
  options: any = {},
) {
  const axios = useAxios();

  const { show, pagination, ...remainingParams } = params;
  const navigate = useNavigate();
  const {logout} = useAuthState()
  const location = useLocation();

  const { page, per_page } = PaginationParams(location);

  const paramToSend = pagination
    ? { ...remainingParams, page: page, per_page: per_page }
    : { ...remainingParams };



  return useQuery(
    [KEY, paramToSend, show],
    async () => {
      const response = await axios.get(url + (show ? `/${show}` : ""), {
        params: paramToSend,
      });
      return response?.data ?? [];
    },
    {
   
      refetchOnWindowFocus: false,
      ...options,
      onError: (error: any) => {
        if (error?.response?.status === 401 || error?.response?.status === 403) {
          logout();
          navigate("/auth");
        }
      },
    }

  );
  
}


export default useGetQueryPagination;
