import { useMutation } from 'react-query';

import { logEvent } from 'src/config/logging';
import { queryClient } from 'src/config/react-query';
import { initCourseTask } from 'src/services/courses';
import { EventName } from 'src/types/amplitude';
import { type RequestError, type RequestSuccess } from 'src/types/services';

import { coursesKeys } from '../queries';
import { type Course, type Task } from '../types';

export type SuccessResponse = RequestSuccess<typeof initCourseTask>;
export type ErrorResponse = RequestError;
export type Values = void;

export const useInitTask = (
  course: Course | undefined,
  task: Task | undefined,
) => {
  const taskId = task?.id || '';
  const taskTag = task?.tag || '';
  const courseId = course?.id || '';

  return useMutation<SuccessResponse, ErrorResponse, Values>(
    coursesKeys.lessons.init(taskId, taskTag),
    () => initCourseTask(taskId, taskTag),
    {
      onSuccess: async () => {
        logEvent(EventName.COURSE_TASK_STARTED, {
          courseId,
          taskId,
          taskTag,
          taskType: task?.type,
        });

        queryClient.refetchQueries(coursesKeys.detail.course(courseId));
        await queryClient.refetchQueries(
          coursesKeys.lessons.lesson(taskId, taskTag),
        );
      },
    },
  );
};

export default useInitTask;
