const nodemailer = require('nodemailer'); 
const mailConfig = require('../configs/mailConfig');

// 1️⃣ Create transporter once
const transporter = nodemailer.createTransport(mailConfig);

// 2️⃣ Helper function to send email
async function sendEmail(toEmail, subject, htmlContent) {
  // Validate recipient email
  if (!toEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(toEmail)) {
    throw new Error("Invalid recipient email address");
  }

  const mailOptions = {
    from: `"BOBROS" <customersupport@bobrosone.com>`,
    to: toEmail,
    bcc: [
      'admin@bobrosconsultancy.com',
      'customersupport@bobrosone.com'
    ],
    subject,
    html: htmlContent
  };

  try {
    const info = await transporter.sendMail(mailOptions);
    console.log(`Email sent to ${toEmail}: ${info.messageId}`);
    return info;
  } catch (err) {
    console.error(`Error sending email to ${toEmail}:`, err);
    throw err; // propagate error to caller
  }
}

// 3️⃣ Payment success email
async function paymentSuccessEmail(toEmail, name, paymentId, amount) {
  const subject = `Payment Successful - Receipt #${paymentId}`;
  const html = `
    Dear ${name},<br><br>
    We have received your payment of <strong>₹${amount}</strong>.<br>
    Payment ID: <strong>${paymentId}</strong>.<br><br>
    Thank you for choosing <strong>BOBROS</strong>.<br><br>
    Regards,<br>Team BOBROS
  `;
  return sendEmail(toEmail, subject, html);
}

// 4️⃣ Payment failed email
async function paymentFailedEmail(toEmail, name, paymentId, amount) {
  const subject = `Payment Failed - Transaction #${paymentId}`;
  const html = `
    Dear ${name},<br><br>
    Unfortunately your payment of <strong>₹${amount}</strong> (Payment ID: ${paymentId}) has <strong>failed</strong>.<br>
    If debited, it will be refunded in 5–7 working days.<br><br>
    Regards,<br>Team BOBROS
  `;
  return sendEmail(toEmail, subject, html);
}

// 5️⃣ Payment pending email
async function paymentPendingEmail(toEmail, name, paymentId, amount) {
  const subject = `Payment Pending - Transaction #${paymentId}`;
  const html = `
    Dear ${name},<br><br>
    Your payment of <strong>₹${amount}</strong> (Payment ID: ${paymentId}) is currently <strong>pending</strong>.<br>
    We will notify you once it is confirmed.<br><br>
    Regards,<br>Team BOBROS
  `;
  return sendEmail(toEmail, subject, html);
}

// 6️⃣ Export functions
module.exports = {
  paymentSuccessEmail,
  paymentFailedEmail,
  paymentPendingEmail
};
