const nodeMailer = require("nodemailer");
const { emailValidator } = require("./email-validator");
const MessagesLogs = require("../models/MessagesLogs");
const Customers = require("../models/Customers");

const transporter = nodeMailer.createTransport({
  host: "mail.buildhub.ph",
  port: 465,
  secure: true,
  auth: {
    user: "info@buildhub.ph",
    pass: "bruFGBg^Ij#{",
  },
});

const emailBuilder = async (receiverArray, ccArray, emailSubject, isHtml = false, emailBody, attachmentsArray) => {
  const receiverString = receiverArray.join(",");
  const ccString = ccArray.join(",");

  const mailOptions = {
    from: "info@buildhub.ph",
    to: `${receiverString}`,
    cc: `${ccString}`,
    subject: emailSubject,
  };
  isHtml ? (mailOptions.html = emailBody) : (mailOptions.text = emailBody);
  attachmentsArray.length > 0 ? (mailOptions.attachments = attachmentsArray) : null;

  const whiteListedDomains = ["buildhub.ph"];
  const receiverDomain = receiverArray[0].split("@")[1];

  try {
    let isValidEmail = true;
    let error = null;
    let mailResponse = null;

    if (!whiteListedDomains.includes(receiverDomain)) {
      const emailValidatorResponse = await emailValidator(receiverArray[0]);
      ({ isValidEmail, error } = emailValidatorResponse);
    }

    if (error) return error;
    if (isValidEmail) {
      mailResponse = await transporter.sendMail(mailOptions);
      // const mailResponse = { success: true };
    }

    // Logs
    const customer = await Customers.findOne({
      where: {
        email: receiverArray[0],
      },
    });
    let customerId = 0;
    if (customer) customerId = customer.id;

    const log = await MessagesLogs.create({
      customer_id: customerId,
      type: "Email",
      receiver: receiverArray[0],
      content: emailBody,
      is_sent: mailResponse ? true : false,
    });
    return mailResponse;

    // Logs
  } catch (err) {
    console.error(err);
    return err;
  }
};

module.exports = emailBuilder;
