import { type UseMutationOptions, useMutation } from 'react-query';

import { duplicateCourse } from 'src/pages/dashboard/Learning/Courses/services';
import { type RequestError, type RequestSuccess } from 'src/types/services';
import { LogEvents, logEvent } from 'src/utils/logging';

import { throwNoCourseSelected } from '../List/utils';
import { type CourseListItem } from '../types';

export type TData = RequestSuccess<typeof duplicateCourse>;
export type TError = RequestError;
export type TValues = undefined;

const useDuplicateCourse = (
  selected: CourseListItem | null,
  options?: UseMutationOptions<TData, TError, TValues>,
) => {
  return useMutation<TData, TError, TValues>(
    () => {
      if (!selected?.id) return throwNoCourseSelected();
      return duplicateCourse(selected.id);
    },
    {
      ...options,
      onSuccess: (response, course, context) => {
        options?.onSuccess?.(response, course, context);

        const newCourse = response.data;

        logEvent(LogEvents.COURSE_DUPLICATED, {
          courseId: newCourse.id,
          courseName: newCourse.title,
          originCourseId: selected?.id,
        });
      },
    },
  );
};

export default useDuplicateCourse;
