const nodemailer = require("nodemailer");
const ejs = require("ejs");
const path = require("path");
const envCredential = require("../config");
const EMAIL_HOST = envCredential.EMAIL_HOST;
const EMAIL_PORT = envCredential.EMAIL_PORT;
const EMAIL_USERNAME = envCredential.EMAIL_USERNAME;
const EMAIL_PASSWORD = envCredential.EMAIL_PASSWORD;

const transport = nodemailer.createTransport({
  host: EMAIL_HOST,
  port: EMAIL_PORT,
  auth: {
    user: EMAIL_USERNAME,
    pass: EMAIL_PASSWORD,
  },
});

const sendEmail = async (template, payload) => {
  let templatePath = path.join(__dirname, "../", "views/emails/", template);
  ejs.renderFile(templatePath, payload, (err, data) => {
    if (err) {
      console.log(err);
    } else {
      var mailOptions = {
        from: `Homguru ${EMAIL_USERNAME}`,
        to: payload?.to,
        subject: payload?.subject,
        html: data,
      };

      transport.sendMail(mailOptions, (error, info) => {
        if (error) {
          return console.log(error);
        }
        console.log("Message sent: %s", info.messageId);
        return true;
      });
    }
  });
};

module.exports = sendEmail;
