import { type UseInfiniteQueryOptions, useInfiniteQuery } from 'react-query';

import { type AxiosResponse } from 'axios';

import { getPublicUsers } from 'src/services/users';
import { getIssuerRequestsList } from 'src/services/vacations';
import { type User } from 'src/types/user';
import { type SectionsManager } from 'src/types/vacations';
import { type PaginatedResponse } from 'src/utils/pagination';

import { vacationsKeys } from '../queries';

type TQueryFnData = AxiosResponse<PaginatedResponse<User>>;

type UsersListQueryKey = ReturnType<typeof vacationsKeys.usersList>;

type Options = Omit<
  UseInfiniteQueryOptions<
    TQueryFnData,
    null,
    AxiosResponse<PaginatedResponse<User>>,
    TQueryFnData,
    UsersListQueryKey
  >,
  'queryKey' | 'queryFn'
>;

type Params = {
  search: string;
  type: SectionsManager;
  isManagerView: boolean;
  visibility: Record<string, boolean>;
};

const useInfinitePeople = (params: Params, extraUseQueryParams?: Options) => {
  const { search, type, isManagerView, visibility } = params;
  return useInfiniteQuery(
    vacationsKeys.usersList(search, type, isManagerView),
    ({ pageParam = 1 }) => {
      if (isManagerView) {
        return getIssuerRequestsList(search, pageParam, 30, type, visibility);
      }

      return getPublicUsers({
        page: pageParam,
        limit: 30,
        search,
      });
    },
    {
      getNextPageParam: lastPage =>
        lastPage.data.page < lastPage.data.totalPages
          ? lastPage.data.page + 1
          : undefined,
      ...extraUseQueryParams,
    },
  );
};

export default useInfinitePeople;
