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

'use strict';

const path = require('path');

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

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

class StickerDeleteJob extends SiteWorkerProcess {

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

  constructor (worker) {
    super(worker, StickerDeleteJob.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: 'sticker-ingest' });
    this.queue.process('sticker-delete', 1, this.processStickerDelete.bind(this));
  }

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

  async processStickerDelete (job) {
    const { minio: minioService, sticker: stickerService } = this.dtp.services;
    try {
      const sticker = await stickerService.getById(job.data.stickerId, true);

      this.log.info('removing original media', { stickerId: sticker._id, slug: sticker.slug });
      await minioService.removeObject(sticker.original.bucket, sticker.original.key);
  
      if (sticker.encoded) {
        this.log.info('removing encoded media', { stickerId: sticker._id, slug: sticker.slug });
        await minioService.removeObject(sticker.encoded.bucket, sticker.encoded.key);
      }
  
      this.log.info('removing sticker', { stickerId: sticker._id, slug: sticker.slug });
      await Sticker.deleteOne({ _id: sticker._id });
    } catch (error) {
      this.log.error('failed to delete sticker', { stickerId: job.data.stickerId, error });
      throw error; // for job report
    }
  }
}

module.exports = StickerDeleteJob;