import { type UseQueryOptions, useQuery } from 'react-query';

import { type AxiosResponse } from 'axios';

import { getCourse } from 'src/pages/dashboard/Learning/Courses/services';
import { type RequestError, type RequestSuccess } from 'src/types/services';

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

export type TSuccess = RequestSuccess<typeof getCourse>;
export type TError = RequestError;
export type TData = TSuccess['data'];
export type TParams = {
  courseId: number | undefined;
  options?: UseQueryOptions<AxiosResponse<TData>, TError, TData>;
};

const useGetCourse = ({ courseId, options }: TParams) => {
  return useQuery<TSuccess, TError, TData>(
    coursesKeys.detail.course(courseId!),
    () => {
      if (!courseId) throw new Error('Course ID is required');
      return getCourse(courseId);
    },
    {
      ...options,
      select: response => response?.data,
      enabled: !!courseId && options?.enabled,
    },
  );
};

export default useGetCourse;
