import nodemailer from "nodemailer";

const transporter = nodemailer.createTransport({
  host: process.env.MAIL_DOMAIN,
  port: process.env.MAIL_PORT,
  secure: false,
  auth: {
    user: process.env.MAIL_USER,
    pass: process.env.MAIL_PASS,
  },
  tls: {
    rejectUnauthorized: false,
    ignoreTLS: false,
    requireTLS: true,
  },
});

let send = async (req, res) => {
  const {
    firma,
    anrede,
    titel,
    vorname,
    nachname,
    email,
    telefon,
    betreff,
    nachricht,
  } = req.body;

  const mailerRes = await mailer({
    firma,
    anrede,
    titel,
    vorname,
    nachname,
    email,
    telefon,
    betreff,
    nachricht,
  });
  res.send(mailerRes);
};

const mailer = ({
  firma,
  anrede,
  titel,
  vorname,
  nachname,
  email,
  telefon,
  betreff,
  nachricht,
}) => {
  let from = "";
  let message = "";

  if (firma) {
    message += `${firma} <br>`;
  }

  if (anrede) {
    message += `${anrede} `;
  }

  if (titel) {
    message += titel + " ";
  }

  if (vorname) {
    message += vorname + " ";
  }

  from += `${nachname} <${email}>`;
  message += `${nachname} <br> ${email} <br><br><h3>${betreff}</h3><p>${nachricht}</p>`;

  const mail = {
    from,
    to: process.env.MAIL_TO,
    subject: `${betreff}`,
    html: message,
    replyTo: email,
  };

  return new Promise((resolve, reject) => {
    transporter.sendMail(mail, (error, info) =>
      error ? reject(error) : resolve(info)
    );
  });
};


export default send