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

'use strict';

const path = require('path');

const mongoose = require('mongoose');

const ChatMessage = mongoose.model('ChatMessage');

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

class ChatRoomClearJob extends SiteWorkerProcess {

  static get COMPONENT ( ) {
    return {
      name: 'charRoomClearJob',
      slug: 'chat-room-clear-job',
    };
  }

  constructor (worker) {
    super(worker, ChatRoomClearJob.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-clear' });
    this.queue.process('chat-room-clear', this.processChatRoomClear.bind(this));
  }

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

  async processChatRoomClear (job) {
    const { roomId } = job.data;
    this.log.info('received chat room clear job', { id: job.id, roomId });
    await ChatMessage
      .find({ room: roomId })
      .cursor()
      .eachAsync(this.worker.deleteChatMessage.bind(this), 4);
  }
}

module.exports = ChatRoomClearJob;