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

'use strict';

const { SiteService } = require('../../lib/site-lib');

class LoganService extends SiteService {

  constructor (dtp) {
    super(dtp, module.exports);
  }

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

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

    this.log.info('creating Logan client');
    this.logan = new LoganClient();

    this.log.info('initializing Logan client');
    await this.logan.initialize({
      log: this.log,
      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,
      },
      request: {
        userField: 'user',
        userIdField: '_id',
        usernameField: 'username',
      },
      flags: {
        includeHostname: true,
        includeClientIpAddress: true,
        includeUser: true,
      },
      queue: {
        enabled: true,
        name: process.env.DTP_LOGAN_QUEUE_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,
          removeOnComplete: true,
          removeOnFail: true,
        },
      },
    });
  }

  async sendRequestEvent (component, req, event) {
    return this.logan.sendRequestEvent(component, req, event);
  }

  async sendEvent (component, event) {
    return this.logan.sendEvent(component, event);
  }
}

module.exports = {
  logId: 'svc:logan',
  index: 'logan',
  className: 'LoganService',
  create: (dtp) => { return new LoganService(dtp); },
};