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

export let onCreateRoomMessageEventSubscriptionHandler: WorkspaceChangeSubscriptionSpecificHandler =
  (cache, event: WorkspaceSubscriptionRoomMessageEventRecord) => {
    let msg: MessageRecord = {
      id: event.messageId,
      posterId: event.posterId,
      content: <string>event.content,
      edited: <boolean>event.edited,
      reactions: {},
    };

    let messages = cache.getCacheDataByRequest({
      query: roomMessagesQuery,
      variables: {
        roomId: event.id,
      },
    });

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

    messages.unshift(msg);

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