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

'use strict';

const path = require('path');

const mongoose = require('mongoose');
const Attachment = mongoose.model('Attachment');

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

class AttachmentDeleteJob extends SiteWorkerProcess {

  static get COMPONENT ( ) {
    return {
      name: 'attachmentDeleteJob',
      slug: 'attachment-delete-job',
    };
  }

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

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

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

    this.log.info('registering job processor', { queue: this.queue.name, name: 'attachment-delete' });
    this.queue.process('attachment-delete', 1, this.processAttachmentDelete.bind(this));
  }

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

  async processAttachmentDelete (job) {
    try {
      const { attachment: attachmentService } = this.dtp.services;
      const attachment = job.data.attachment = await attachmentService.getById(
        job.data.attachmentId,
        { withOriginal: true },
      );
  
      await this.deleteAttachmentFile(attachment, 'processed');
      await this.deleteAttachmentFile(attachment, 'original');

      this.log.info('deleting attachment', { _id: attachment._id });
      await Attachment.deleteOne({ _id: attachment._id });
    } catch (error) {
      this.log.error('failed to delete attachment', { attachmentId: job.data.attachmentId, error });
      throw error;
    }
  }

  async deleteAttachmentFile (attachment, which) {
    this.log.info('removing attachment file', { _id: attachment._id, which });

    const file = attachment[which];
    if (!file || !file.bucket || !file.key) {
      return;
    }

    const { minio: minioService } = this.dtp.services;
    await minioService.removeObject(file.bucket, file.key);
  }
}

module.exports = AttachmentDeleteJob;