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

import { notifyCourseAudience } 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, NotificationTypes } from '../types';

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

const useNotifyCourseAudience = (
  selected: CourseListItem | null,
  options?: UseMutationOptions<TData, TError, TValues>,
) => {
  return useMutation<TData, TError, TValues>(
    () => {
      if (!selected?.id) return throwNoCourseSelected();
      return notifyCourseAudience(selected.id);
    },
    {
      ...options,
      onSuccess: (data, values, context) => {
        options?.onSuccess?.(data, values, context);

        logEvent(LogEvents.COURSE_NOTIFICATION_SENT, {
          courseId: selected?.id,
          notificationType: NotificationTypes.PENDING,
        });
      },
    },
  );
};

export default useNotifyCourseAudience;
