import nodemailer from "nodemailer";
import dotenv from "dotenv";

dotenv.config();

export const sendEmail = async (email, subject, text) => {
  try {
    const transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST,
      port: parseInt(process.env.SMTP_PORT),
      secure: process.env.SMTP_SECURE === "true",
      socketTimeout: parseInt(process.env.SMTP_SOCKET_TIMEOUT),
      logger: process.env.SMTP_LOGGER === "true",
      debug: process.env.SMTP_DEBUG === "true",
      secureConnection: process.env.SMTP_SECURE_CONNECTION === "true",
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS,
      },
      tls: {
        rejectUnauthorized: true,
      },
    });

    await transporter.sendMail({
      from: {
        name: process.env.SMTP_FROM_NAME,
        address: process.env.SMTP_FROM,
      },
      to: email,
      subject: subject,
      text: text,
    });

    // console.log("Email sent successfully");
  } catch (error) {
    console.log("Email not sent!");
    console.error(error);
    return error;
  }
};
