import { MessageRecord } from '../../../../../../../../server-services/query-records/room-records';
import { WorkspaceSubscriptionDialogueMessageEventRecord } from '../../../../../../../../server-services/query-records/workspace-records';
import { dialogueMessagesQuery } from '../../../../../../../../server-services/querys';
import { WorkspaceChangeSubscriptionSpecificHandler } from '../types';

export let onCreateDialogueMessageEventSubscriptionHandler: WorkspaceChangeSubscriptionSpecificHandler =
  (cache, event: WorkspaceSubscriptionDialogueMessageEventRecord) => {
    let messages = cache.getCacheDataByRequest({
      query: dialogueMessagesQuery,
      variables: {
        peerId: event.id,
      },
    });

    if (!messages) {
      messages = [];
      cache.setCacheDataByRequest(
        {
          query: dialogueMessagesQuery,
          variables: {
            peerId: event.id,
          },
        },
        messages
      );
    }

    let msg: MessageRecord = {
      id: event.messageId,
      posterId: event.posterId,
      content: <string>event.content,
      edited: <boolean>event.edited,
      reactions: {},
    };

    messages.unshift(msg);

    if (!cache.getCacheData('messages')[event.id]) {
      cache.getCacheData('messages')[event.id] = {};
    }
    cache.getCacheData('messages')[event.id][msg.id] = msg;
  };
