import { useInfiniteQuery } from 'react-query';

import { useDebounce } from '@material-hu/hooks/useDebounce';

import { getCourses } from 'src/pages/dashboard/Learning/Courses/services';
import { type RequestError, type RequestSuccess } from 'src/types/services';
import { sToMs } from 'src/utils/timeUtils';

import { CourseStatus } from '../../Courses/types';
import { SortingOrder, TableColumns } from '../../common/types';
import { PATHS_COURSES_LIMIT } from '../constants';
import { pathsKeys } from '../queries';

export type TSuccess = RequestSuccess<typeof getCourses>;
export type TError = RequestError;
export type TData = TSuccess;

const useGetPathCourses = (query: string) => {
  const debouncedQuery = useDebounce(query);

  const params = {
    q: debouncedQuery || undefined,
    order: SortingOrder.DESC,
    orderBy: TableColumns.lastModified,
    limit: PATHS_COURSES_LIMIT,
    status: CourseStatus.ACTIVE,
  };

  return useInfiniteQuery<TSuccess, TError, TData>({
    queryKey: pathsKeys.courses.list(params),
    queryFn: ({ pageParam = 1 }) => getCourses({ ...params, page: pageParam }),
    getNextPageParam: lastPage =>
      lastPage.data.page === lastPage.data.totalPages
        ? undefined
        : lastPage.data.page + 1,
    staleTime: sToMs(60),
  });
};

export default useGetPathCourses;
