const nodemailer = require("nodemailer");
const logger = require("../handlers/logger"); // Import the logger

const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: process.env.SMTP_PORT,
  secure: false,
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASS,
  },
});

// Reusable sendEmail function
async function sendEmail(
  recipients,
  subject,
  textContent = "",
  htmlContent = ""
) {
  try {
    if (!Array.isArray(recipients)) {
      recipients = [recipients];
    }

    // Automatically set textContent if only HTML is provided
    if (!textContent && htmlContent) {
      textContent = htmlContent.replace(/<[^>]*>?/gm, ""); // Strip HTML tags
    }

    // Automatically set htmlContent if only text is provided
    if (!htmlContent && textContent) {
      htmlContent = `<p>${textContent.replace(/\n/g, "<br>")}</p>`; // Convert new lines to <br>
    }

    const info = await transporter.sendMail({
      from: `${process.env.hosp_name} <dr_hassan@nawalhospital.com.ng>`,
      to: recipients.join(","),
      subject,
      text: textContent, // Ensures an email can be read as plain text
      html: htmlContent, // Ensures emails render properly in HTML clients
    });

    //console.log(`Email sent to: ${recipients.join(', ')}`);
    return info.messageId;
  } catch (error) {
    logger.error("Error sending email", { error }); // Log errors
    //throw error; // Allow the caller to handle errors
  }
}

module.exports = sendEmail;

// async function sendEmail(recipients, subject, textContent = "", htmlContent = "") {
//     try {
//         if (!Array.isArray(recipients)) {
//             recipients = [recipients];
//         }

//         // Automatically set textContent if only HTML is provided
//         if (!textContent && htmlContent) {
//             textContent = htmlContent.replace(/<[^>]*>?/gm, ''); // Strip HTML tags
//         }

//         // Automatically set htmlContent if only text is provided
//         if (!htmlContent && textContent) {
//             htmlContent = `<p>${textContent.replace(/\n/g, "<br>")}</p>`; // Convert new lines to <br>
//         }

//         const info = await transporter.sendMail({
//             from: `"Your App Name" <${process.env.SMTP_USER}>`,
//             to: recipients.join(','),
//             subject,
//             text: textContent, // Ensures an email can be read as plain text
//             html: htmlContent, // Ensures emails render properly in HTML clients
//         });

//         console.log(`Email sent to: ${recipients.join(', ')}`);
//         return info.messageId;
//     } catch (error) {
//         logErrorToFile(error); // Log errors
//         throw error; // Allow the caller to handle errors
//     }
// }
