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

'use strict';

const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '..', '..', '.env') });

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

module.pkg = require(path.resolve(__dirname, '..', '..', 'package.json'));
module.config = {
  component: { name: 'newsletterWorker', slug: 'newsletter-worker' },
  root: path.resolve(__dirname, '..', '..'),
};

class NewsletterWorker extends SiteWorker {

  constructor (dtp) {
    super(dtp, dtp.config.component);
    this.newsletters = { };
  }

  async start ( ) {
    await super.start();
    
    await this.loadProcessor(path.join(__dirname, 'newsletter', 'job', 'transmit.js'));
    await this.loadProcessor(path.join(__dirname, 'newsletter', 'job', 'email-send.js'));

    await this.startProcessors();
  }

  async stop ( ) {
    if (this.jobQueue) {
      this.log.info('stopping newsletter job queue');
      await this.jobQueue.close();
      delete this.jobQueue;
    }
    await super.stop();
  }

  async loadNewsletter (newsletterId) {
    const { newsletter: newsletterService } = this.dtp.services;
    let newsletter = this.newsletters[newsletterId];
    if (!newsletter) {
      newsletter = await newsletterService.getById(newsletterId);
      this.newsletters[newsletterId] = newsletter;
    }
    return newsletter;
  }
}  

(async ( ) => {
  try {
    module.log = new SiteLog(module, module.config.component);

    module.worker = new NewsletterWorker(module);
    await module.worker.start();

    module.log.info(`${module.pkg.name} v${module.pkg.version} ${module.config.component.name} started`);
  } catch (error) {
    module.log.error('failed to start Newsletter worker', { error });
    process.exit(-1);
  }
})();
