// chat/job/chat-room-delete.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

const path = require('path');

const mongoose = require('mongoose');

const ChatRoom = mongoose.model('ChatRoom');
const ChatRoomInvite = mongoose.model('ChatRoomInvite');
const ChatMessage = mongoose.model('ChatMessage');
const EmojiReaction = mongoose.model('EmojiReaction');

const { SiteWorkerProcess } = require(path.join(__dirname, '..', '..', '..', '..', 'lib', 'site-lib'));

/**
 * DTP Core Chat sticker processor can receive requests to ingest and delete
 * stickers to be executed as background jobs in a queue. This processor
 * attaches to the `media` queue and registers processors for `sticker-ingest`
 * and `sticker-delete`.
 */
class ChatRoomDeleteJob extends SiteWorkerProcess {

  static get COMPONENT ( ) {
    return {
      name: 'chatRoomProcessor',
      slug: 'chat-room-processor',
    };
  }

  constructor (worker) {
    super(worker, ChatRoomDeleteJob.COMPONENT);
  }

  async start ( ) {
    await super.start();

    this.queue = await this.getJobQueue('chat', this.dtp.config.jobQueues.chat);

    this.log.info('registering job processor', { queue: this.queue.name, name: 'chat-room-delete' });
    this.queue.process('chat-room-delete', this.processChatRoomDelete.bind(this));
  }

  async stop ( ) {
    await super.stop();
  }

  async processChatRoomDelete (job) {
    const { roomId } = job.data;
    this.log.info('received chat room delete job', { id: job.id, roomId });

    await EmojiReaction
      .find({ subject: roomId })
      .cursor()
      .eachAsync(this.deleteEmojiReaction.bind(this));

    await ChatMessage
      .find({ room: roomId })
      .cursor()
      .eachAsync(this.worker.deleteChatMessage.bind(this), 4);

    await ChatRoomInvite
      .find({ room: roomId })
      .cursor()
      .eachAsync(this.deleteChatRoomInvite.bind(this), 4);
    
    await ChatRoom.deleteOne({ _id: roomId });
  }

  async deleteEmojiReaction (reaction) {
    if (!reaction || !reaction._id) {
      this.log.error('skipping invalid emoji reaction for delete');
      return;
    }

    const EmojiReaction = mongoose.model('EmojiReaction');
    try {
      await EmojiReaction.deleteOne({ _id: reaction._id });
    } catch (error) {
      this.log.error('failed to delete chat message', { reactionId: reaction._id, error });
    }
  }

  async deleteChatRoomInvite (invite) {
    if (!invite || !invite._id) {
      this.log.error('skipping invalid invite for delete');
      return;
    }

    const ChatRoomInvite = mongoose.model('ChatRoomInvite');
    try {
      await ChatRoomInvite.deleteOne({ _id: invite._id });
    } catch (error) {
      this.log.error('failed to delete chat room invite', { inviteId: invite._id, error });
    }
  }

}

module.exports = ChatRoomDeleteJob;