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

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

import { formatCreateDraftData } from '../New/utils';
import { Steps, type StepsTypes } from '../types';

export type TSuccess = RequestSuccess<typeof createDraft>;
export type TError = RequestError;
export type TValues = StepsTypes;

type TParams = {
  options?: UseMutationOptions<TSuccess, TError, TValues>;
};

const useCreateDraftMutation = ({ options }: TParams = {}) => {
  return useMutation<TSuccess, TError, TValues>(
    async (values: StepsTypes) => {
      const basicInformation = values[Steps.BASIC_INFORMATION];
      const payload = await formatCreateDraftData(basicInformation);
      return createDraft(payload);
    },
    {
      onSuccess: (response, variables, context) => {
        const courseId = response.data.id;
        logEvent(LogEvents.NEW_COURSE_DRAFT_CREATED, { courseId });
        options?.onSuccess?.(response, variables, context);
      },
    },
  );
};

export default useCreateDraftMutation;
