import { useMutation } from 'react-query';

import { type AxiosResponse } from 'axios';

import { logEvent } from 'src/config/logging';
import { queryClient } from 'src/config/react-query';
import { EventName } from 'src/types/amplitude';

import { sessionsKeys } from '../queries';
import { confirmSessionAttendance } from '../services';
import {
  type ConfirmSessionAttendanceParams,
  type SessionDetail,
} from '../types';

export const useConfirmAttendance = (sessionId: number) => {
  return useMutation({
    mutationFn: confirmSessionAttendance,
    onMutate: async (variables: ConfirmSessionAttendanceParams) => {
      const queryKey = sessionsKeys.detail(sessionId);

      await queryClient.cancelQueries({ queryKey });

      const previousSession =
        queryClient.getQueryData<AxiosResponse<SessionDetail>>(queryKey);

      if (previousSession) {
        queryClient.setQueryData<AxiosResponse<SessionDetail>>(queryKey, {
          ...previousSession,
          data: {
            ...previousSession.data,
            confirmedAssistance: variables.assisted,
          },
        });
      }

      return { previousSession };
    },
    onSuccess: () => logEvent(EventName.SESSION_CONFIRM, { sessionId }),
    onError: (_error, _variables, context) => {
      if (context?.previousSession) {
        queryClient.setQueryData(
          sessionsKeys.detail(sessionId),
          context.previousSession,
        );
      }
    },
    onSettled: () => {
      queryClient.invalidateQueries(sessionsKeys.detail(sessionId));
      queryClient.invalidateQueries(sessionsKeys.sessions.all());
    },
  });
};
