import { useMutation } from 'react-query';

import { type AxiosError } from 'axios';

import useSnackbar from '@material-hu/components/design-system/Snackbar';

import {
  deleteShiftRotation,
  ShiftRotationErrorCodes,
} from 'src/services/shifts';
import { type ResponseError } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { invalidateShiftRotations, removeShiftRotation } from '../queries';

export const useDeleteShiftRotationMutation = () => {
  const { t } = useLokaliseTranslation('shifts');
  const { enqueueSnackbar } = useSnackbar();

  return useMutation({
    mutationFn: deleteShiftRotation,
    onSuccess: async (_response, id) => {
      removeShiftRotation(id);
      await invalidateShiftRotations();
      enqueueSnackbar({
        title: t('templates.feedback.success_delete'),
        variant: 'success',
      });
    },
    onError: async (error: AxiosError<ResponseError>) => {
      // The rotation is already gone — refresh the list so the stale row drops
      // and skip the error toast: from the user's perspective it was deleted.
      if (
        error?.response?.data?.code ===
        ShiftRotationErrorCodes.SHIFT_ROTATION_NOT_FOUND
      ) {
        await invalidateShiftRotations();
        return;
      }
      enqueueSnackbar({
        title: t('templates.feedback.error_delete'),
        description: t('actions.try_again'),
        variant: 'error',
      });
    },
  });
};
