import { useQuery } from 'react-query';
import { useNavigate } from 'react-router';

import useGeneralError from 'src/hooks/useGeneralError';
import { getCourseAudience } from 'src/pages/dashboard/Learning/Courses/services';
import { type RequestError, type RequestSuccess } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { coursesKeys } from '../queries';
import { coursesRoutes } from '../routes';

export type TSuccess = RequestSuccess<typeof getCourseAudience>;
export type TError = RequestError;
export type TData = TSuccess['data'];

const useGetAudience = (courseId: number | undefined) => {
  const navigate = useNavigate();
  const { t } = useLokaliseTranslation('learning');
  const showGeneralError = useGeneralError();

  return useQuery<TSuccess, TError, TData>(
    coursesKeys.detail.audience(courseId!),
    () => {
      if (!courseId) throw new Error('Course ID is required');
      return getCourseAudience(courseId);
    },
    {
      onError: err => {
        navigate(coursesRoutes.base());
        showGeneralError(err, t('general:not_found'));
      },
      enabled: !!courseId,
      select: response => response?.data,
    },
  );
};

export default useGetAudience;
