// newsletter/job/email-send.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

const path = require('path');

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

class NewsletterEmailSendJob extends SiteWorkerProcess {

  static get COMPONENT ( ) {
    return {
      name: 'newsletterEmailSendJob',
      slug: 'newsletter-email-send-job',
    };
  }

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

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

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

    this.log.info('registering job processor', { queue: this.queue.name, name: 'email-send' });
    this.queue.process('email-send', this.processEmailSend.bind(this));
  }

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

  async processEmailSend (job) {
    const { email: emailService } = this.dtp.services;
    const { newsletterId, recipient } = job.data;

    try {
      let newsletter = await this.worker.loadNewsletter(newsletterId);
      if (!newsletter) {
        throw new Error('newsletter not found');
      }
  
      const result = await emailService.send({
        from: process.env.DTP_EMAIL_SMTP_FROM || `noreply@${this.dtp.config.site.domainKey}`,
        to: recipient,
        subject: newsletter.title,
        html: newsletter.content.html,
        text: newsletter.content.text,
      });
  
      this.jobLog(job, 'newsletter email sent', { result });
    } catch (error) {
      this.log.error('failed to send newsletter email', { newsletterId, recipient, error });
      throw error; // throw error to Bull so it can report in job reports
    }
  }
}

module.exports = NewsletterEmailSendJob;