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

export let onDeleteRoomMessageEventSubscriptionHandler: WorkspaceChangeSubscriptionSpecificHandler =
  (cache, event: WorkspaceSubscriptionRoomMessageEventRecord) => {
    let messages = cache.getCacheDataByRequest({
      query: roomMessagesQuery,
      variables: {
        roomId: event.id,
      },
    });

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

    for (let i = 0; i < messages.length; i++) {
      if (messages[i].id == event.messageId) {
        messages.splice(i, 1);
        break;
      }
    }

    if (cache.getCacheData('messages')[event.id]) {
      delete cache.getCacheData('messages')[event.id][event.messageId];
    }
  };
