import {useMutation} from 'react-query';
import {Conversation} from '@modules/chats/interfaces';
import {ConversationOpenParams} from '@modules/chats/services/interfaces';
import {openConversation as openConversationService} from '@modules/chats/services';
import {ConversationsUpdaterService} from '@modules/chats/instances/updaters';
import {getUlid, logAmplitudeEvent} from '@shared/utils';
import {AMPLITUDE_EVENTS} from '@shared/constants';

import {AmplitudeConversationTypes} from '../constants';

export const useOpenConversation = (
  onSuccess?: (response: Conversation) => void,
  onError?: () => void,
) => {
  const {mutate: openConversation, isLoading} = useMutation(
    async (params: ConversationOpenParams) => {
      const idempotencyKey = getUlid();
      const response = await openConversationService(params, idempotencyKey);

      logAmplitudeEvent(AMPLITUDE_EVENTS.CHATS_2_CONVERSATION_OPENED, {
        conversationType: response.is_im
          ? AmplitudeConversationTypes.Individual
          : AmplitudeConversationTypes.Group,
        conversationID: response.id,
      });

      // Save new conversation to the DB (even if no_op is true, we're not sure if the conversation exists in the DB)
      await ConversationsUpdaterService.saveNewConversation(response);
      return response;
    },
    {
      onSuccess,
      onError,
    },
  );
  return {openConversation, isLoading};
};
