import { useMutation } from 'react-query';

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

import {
  CreateOrUpdateShiftRotationVC,
  updateShiftRotation,
} from 'src/services/shifts';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

type UpdateShiftRotationParams = {
  id: string;
  data: CreateOrUpdateShiftRotationVC;
};

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

  return useMutation({
    mutationFn: ({ id, data }: UpdateShiftRotationParams) =>
      updateShiftRotation(id, data),
    onSuccess: async (_response, { id }) => {
      // Refresh the list and drop the stale cached graph so reopening the
      // edit form shows the updated days/shifts (not just name/description).
      removeShiftRotation(id);
      await invalidateShiftRotations();
      enqueueSnackbar({
        title: t('templates.feedback.success_edit'),
        variant: 'success',
      });
    },
    onError: () => {
      enqueueSnackbar({
        title: t('templates.feedback.error_edit'),
        description: t('actions.try_again'),
        variant: 'error',
      });
    },
  });
};
