import { useMutation } from 'react-query';

import { type AxiosError, type AxiosResponse } from 'axios';

import { queryClient } from 'src/config/react-query';
import {
  deleteModule,
  deleteTask,
  updateCourse,
} from 'src/pages/dashboard/Learning/Courses/services';
import { type ResponseError } from 'src/types/services';
import { LogEvents, logEvent } from 'src/utils/logging';

import { formatUpdateCourseData } from '../New/utils';
import { coursesKeys } from '../queries';
import { type CourseDetail, type UpdateDraftValues } from '../types';

type SuccessResponse = AxiosResponse<CourseDetail>;
export type ErrorResponse = AxiosError<ResponseError>;
export type Values = UpdateDraftValues;

const useUpdateDraftMutation = () => {
  return useMutation<SuccessResponse, ErrorResponse, Values>(
    async (payload: UpdateDraftValues) => {
      const { courseId, values, deletedModules, deletedTasks } = payload;

      await Promise.all([
        ...deletedModules.map(moduleId => deleteModule(courseId, moduleId)),
        ...deletedTasks.map(taskId => deleteTask(courseId, taskId)),
      ]);

      return updateCourse(courseId, await formatUpdateCourseData(values));
    },
    {
      onSuccess: (response, payload) => {
        queryClient.setQueryData(
          coursesKeys.detail.course(payload.courseId),
          response,
        );
        logEvent(LogEvents.NEW_COURSE_DRAFT_EDITED, {
          courseId: payload.courseId,
        });
      },
    },
  );
};

export default useUpdateDraftMutation;
