let nodemailer = require("nodemailer");
let htmlToText = require("nodemailer-html-to-text").htmlToText;
const config = require("config");

module.exports = ({ transportType = "smtp", mailOptions }) =>
  new Promise((resolve, reject) => {
    try {
      let configData = {
        host: "smtp.gmail.com",
        port: 465,
        secure: true,
        auth: {
          user: config.get("EMAILID"),
          pass: config.get("EMAILPASSWORD"),
        },
      };

      let transporter;
      if (transportType == "smtp") {
        console.log("IN SMTP");
        transporter = nodemailer.createTransport(configData);
      } else if (transportType == "mailgun") {
        console.log("IN MAILGUN");
        let mg = require("nodemailer-mailgun-transport");
        transporter = nodemailer.createTransport(
          mg({
            auth: {
              api_key: configData.mailer.mailgun.apiKey,
              domain: configData.mailer.mailgun.domain,
            },
          })
        );
      } else if (transportType == "sendgrid") {
        console.log("IN SENDGRID");
        let sgTransport = require("nodemailer-sendgrid-transport");
        transporter = nodemailer.createTransport(
          sgTransport({
            auth: {
              api_key: configData.mailer.sendgrid.apiKey,
            },
          })
        );
      }

      if (transporter) {
        transporter.use("compile", htmlToText());
        transporter.sendMail(mailOptions, (err, info) => {
          if (err) {
            console.log("Unable to send email: ", err);
            reject(err);
          } else {
            console.log("Email message sent.", info.response);
            resolve(info);
          }
        });
      } else
        reject(
          new Error(
            "Unable to send email! Invalid mailer transport: " + transportType
          )
        );
    } catch (error) {}
  });
