const { isString, isEmpty } = require("lodash");
const { defaultProvider } = require("@aws-sdk/credential-provider-node");
const { InstanceRegion } = require("../utils/instanceMgr");
const aws = require("@aws-sdk/client-ses");
const nodemailer = require("nodemailer");
const logger = require("../utils/logger");

const isLocal = isString(process.env?.LOCALSTACK_HOSTNAME) && !isEmpty(process.env?.LOCALSTACK_HOSTNAME);

const sesConfig = {
  apiVersion: "latest",
  credentials: defaultProvider(),
  region: InstanceRegion()
};

if (isLocal) {
  sesConfig.endpoint = `http://${process.env.LOCALSTACK_HOSTNAME}:4566`;
  logger.logger.debug(`SES Mailer set to LocalStack end point: ${sesConfig.endpoint}`);
}

const ses = new aws.SES(sesConfig);

let transporter = nodemailer.createTransport({
  SES: { ses, aws }
});

module.exports = transporter;
