import {localEventsHandler} from '@config/synchroniser';
import {
  saveNewMessages,
  updateDeliverStatus as updateDeliverStatusDB,
  updateMessageHeightInDb,
} from '@modules/chats/db';
import {DeliverStatus, Message} from '@modules/chats/interfaces';
import {
  updateDeliverStatus as updateDeliverStatusStore,
  updateSentMessage,
  useGroups,
  setMessagesAsLatest,
  updateMessageHeightInStore,
} from '@modules/chats/store/zustand/useGroups';

class MessagesUpdaterServiceClass {
  deleteUnsentMessage = async (message: Message) => {
    const updatedMessage = {
      ...message,
      version: message.version + 1,
      status: undefined,
    };

    // Remove local events related to the message
    localEventsHandler.removeEventsById(message.client_msg_id);

    // Save new version of the message as deleted
    updateSentMessage(updatedMessage);

    // Save new version of the message as deleted
    await this.saveMessages([updatedMessage]);
  };

  saveMessages = (
    messages: Message[],
    options?: {updateStore?: boolean; updateDb?: boolean},
  ) => {
    const {updateStore = false, updateDb = true} = options ?? {};

    if (updateStore) {
      useGroups.getState().updateMessagesBatch(messages);
    }

    if (updateDb) {
      return saveNewMessages(messages);
    }
  };

  setMessagesAsLatest = (messages: Message[]) => {
    setMessagesAsLatest(messages);
  };

  async updateDeliverStatus({
    fromMessageTs,
    toMessageTs,
    channelId,
    deliverStatus,
  }: {
    fromMessageTs: string;
    toMessageTs: string;
    channelId: string;
    deliverStatus: DeliverStatus;
  }): Promise<void> {
    updateDeliverStatusStore({
      fromMessageTs,
      toMessageTs,
      channelId,
      deliverStatus,
    });
    await updateDeliverStatusDB({
      fromMessageTs,
      toMessageTs,
      channelId,
      deliverStatus,
    });
  }

  updateMessageHeight = (
    channelId: string,
    clientMsgId: string,
    height: number,
  ) => {
    updateMessageHeightInStore(channelId, clientMsgId, height);
    updateMessageHeightInDb(clientMsgId, height);
  };
}

export const MessagesUpdaterService = new MessagesUpdaterServiceClass();
