import { useMutation, useQueryClient } from 'react-query';

import { logEvent } from 'src/config/logging';
import { finishCourseTask } 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 EvaluationAnswer,
  type Task,
  TaskFinishedReason,
  TaskStatus,
} from '../types';

export type SuccessResponse = RequestSuccess<typeof finishCourseTask>;
export type ErrorResponse = RequestError;
export type Values = {
  reason?: TaskFinishedReason;
  data?: EvaluationAnswer;
};

export const useFinishTask = (
  course: Course | undefined,
  task: Task | undefined,
) => {
  const queryClient = useQueryClient();

  const taskId = task?.id || '';
  const taskTag = task?.tag || '';
  const courseId = course?.id || '';

  return useMutation<SuccessResponse, ErrorResponse, Values>(
    coursesKeys.lessons.finish(taskId, taskTag),
    ({ data }) => finishCourseTask(taskId, taskTag, data),
    {
      onSuccess: async (
        response,
        { reason = TaskFinishedReason.UNKNOWN, data },
      ) => {
        logEvent(EventName.COURSE_TASK_FINISHED, {
          courseId,
          taskId,
          taskTag,
          taskType: task?.type,
          evaluationPassed: data
            ? response.data.status === TaskStatus.FINISHED_OK
            : undefined,
          reason,
        });

        await queryClient.invalidateQueries(
          coursesKeys.detail.course(courseId),
        );
        await queryClient.invalidateQueries(
          coursesKeys.lessons.lesson(taskId, taskTag),
        );
      },
      onError: () => {},
    },
  );
};

export default useFinishTask;
