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

export default function useGetQueryPagination(KEY: string | string[], Api: string, params: any = {}, options: any = {}, dontSearchBy?: string) {
  const axios = useAxios();
  const location = useLocation();
  let pagination = location?.search || '';
  

  const { logout } = useAuthState();
  const navigate = useNavigate();

  if (dontSearchBy && pagination.includes(dontSearchBy)) {
    const searchParams = new URLSearchParams(pagination);
    searchParams.delete(dontSearchBy);
    pagination = searchParams.toString();
  }
  if (pagination && !pagination.startsWith('?')) {
    pagination = '?' + pagination;
  }
  
  return useQuery(
    [Array.isArray(KEY) ? KEY.join(',') : KEY, pagination], async () => {
      const response = await axios.get(Api + pagination, { params });
      return response.data;
    },
    {
      onError: (error: any) => {
        if (error?.response?.status === 401 || error?.response?.status === 403) {
          logout();
          navigate("/auth");
        }
      },
      refetchOnWindowFocus: false,
      ...options
    }
  );
}
