import { useQuery } from 'react-query';

import { coursesKeys } from 'src/pages/dashboard/learning/courses/queries';
import { getCourseTask } from 'src/services/courses';
import { type RequestError, type RequestSuccess } from 'src/types/services';

export type TSuccess = RequestSuccess<typeof getCourseTask>;
export type TError = RequestError;
export type TData = TSuccess['data'];
export type TParams = {
  taskId?: number;
  tag?: string;
};

const useGetTask = ({ taskId, tag }: TParams) => {
  return useQuery<TSuccess, TError, TData>(
    coursesKeys.lessons.lesson(taskId!, tag!),
    () => {
      if (!taskId || !tag)
        throw new Error('Error: taskId and tag are required');
      return getCourseTask(taskId, tag);
    },
    {
      select: response => response.data,
      enabled: !!taskId && !!tag,
    },
  );
};

export default useGetTask;
