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

import { type AxiosResponse } from 'axios';

import { getCourse } from 'src/services/courses';
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 | string | undefined;
  options?: UseQueryOptions<AxiosResponse<TData>, TError, TData>;
};

const useGetCourse = ({ courseId, options }: TParams) => {
  const id = Number(courseId || '');

  const { data, ...query } = useQuery({
    queryKey: coursesKeys.detail.course(id),
    queryFn: () => getCourse(id),
    select: response => response.data,
    enabled: !!id,
    ...options,
  });

  return { course: data, ...query };
};

export default useGetCourse;
