'use strict';

require('dotenv').config();

const path = require('path');

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

module.rootPath = path.resolve(__dirname, '..', '..');
module.pkg = require(path.resolve(__dirname, '..', '..', 'package.json'));

module.config = {
  environment: process.env.NODE_ENV,
  root: module.rootPath,
  site: require(path.join(module.rootPath, 'config', 'site')),
  component: { logId: 'wrk:logan-site', index: 'loganSite', className: 'LoganSiteWorker' },
};

class LoganSiteWorker extends SiteWorker {

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

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

    const { LoganWorker } = await import('dtp-logan-api');

    this.log.info('creating Logan worker');
    this.loganWorker = new LoganWorker();

    this.log.info('initializing Logan worker');
    await this.loganWorker.initialize({
      api: {
        enabled: process.env.DTP_LOGAN === 'enabled',
        key: process.env.DTP_LOGAN_API_KEY,
        scheme: process.env.DTP_LOGAN_SCHEME,
        host: process.env.DTP_LOGAN_HOST,
      },
      queue: {
        enabled: true,
        name: 'logan',
        redis: {
          host: process.env.REDIS_HOST,
          port: process.env.REDIS_PORT,
          username: process.env.REDIS_USERNAME, // requires Redis >= 6
          password: process.env.REDIS_PASSWORD,
          keyPrefix: process.env.REDIS_PREFIX,
        },
        defaultJobOptions: {
          attempts: 3,
          priority: 10,
          removeOnComplete: true,
          removeOnFail: true,
        },
      },
    });
  }

  async stop ( ) {
    if (this.loganWorker) {
      await this.loganWorker.close();
      delete this.loganWorker;
    }
    await super.stop();
  }
}

(async ( ) => {

  module.log = new SiteLog(module, module.config.component);

  if (!process.env.DTP_LOGAN_API_KEY) {
    console.log('Must define DTP_LOGAN_API_KEY environment variable to run test');
    process.exit(-1);
  }

  try {
    module.worker = new LoganSiteWorker(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 worker', { component: module.config.component, error });
    process.exit(-1);
  }

})();