var nodemailer = require("nodemailer");
require("dotenv").config();

var transporter = nodemailer.createTransport({
  host: process.env.email_server,
  port: 465,
  secure: true, // upgrade later with STARTTLS
  auth: {
    user: process.env.email_api,
    pass: process.env.email_secret
  }
});

// verify connection configuration
transporter.verify(function(error, success) {
  if (error) {
    console.log(error);
  } else {
    console.log("[EMAIL] Succesfully connected to SMTP server.");
  }
});

exports.sendEmail = (req, res) => {
  if (process.env.NODE_ENV !== "production") {
    console.log("[EMAIL] Incoming Message Body", req.body);
  }
  transporter.sendMail(
    {
      ...req.body,
      from: {
        name: req.body.from.name || "No Reply @ Bodyshop.app",
        address: "noreply@bodyshop.app"
      }
    },
    function(error, info) {
      if (error) {
        console.log("[EMAIL] Email send failed. ", error);
        res.json({ success: false, error: error });
      } else {
        console.log("[EMAIL] Email sent: " + info.response);
        res.json({ success: true, response: info.response });
      }
    }
  );
};
