const nodemailer = require('nodemailer');

// Configure Gmail transporter
const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: process.env.GMAIL_USER,      // your Gmail
    pass: process.env.GMAIL_PASS       // Gmail App Password
  }
});

// In-memory rate limit tracker: email → [timestamps]
const emailSendLog = new Map();

// Helper: Can we send this email?
function canSendEmail(email) {
  const now = Date.now();
  const windowTime = 24 * 60 * 60 * 1000; // 24 hours in ms
  const limit = 2;

  const timestamps = emailSendLog.get(email) || [];
  const recent = timestamps.filter(ts => now - ts < windowTime);

  if (recent.length >= limit) return false;

  recent.push(now);
  emailSendLog.set(email, recent);
  return true;
}

// Send acknowledgment email to the user
async function sendAcknowledgementEmail(firstName, email) {
  console.log('Sending acknowledgement email to user:', firstName, email);

  const mailOptions = {
    from: `"GuardianCall.ai" <${process.env.GMAIL_USER}>`,
    to: email,
    subject: 'Welcome to GuardianCall.ai!',
    html: `<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <title>Welcome to GuardianCall.ai</title>
</head>
<body style="font-family: Arial, sans-serif; background-color: #f9f9f9;">
  <table width="100%" cellspacing="0" cellpadding="0">
    <tr>
      <td align="center">
        <table width="600" style="background-color: #ffffff; margin-top: 30px; border-radius: 10px;">
          <tr>
            <td align="center" style="padding: 30px;">
              <img src="https://s3.blr.cloudtopiaa.com:6780/swift/v1/AUTH_02a111ba8aca4efcbc139b77a7b37f30/gaurdian-ui/GuardianCallAi-Logo.png" alt="GuardianCall.ai Logo" style="max-width: 250px;" />
            </td>
          </tr>
          <tr>
            <td style="padding: 30px 40px;">
              <h2 style="color: #333;">Welcome, ${firstName}!</h2>
              <p style="color: #555; font-size: 16px;">
                Thank you for signing up with <strong>GuardianCall.ai</strong>. Your account registration request has been received and is currently under review.
              </p>
              <p style="color: #555; font-size: 16px;">
                Once your account is approved, you'll receive a confirmation email with next steps and login instructions.
              </p>
              <p style="color: #555; font-size: 16px;">
                In the meantime, feel free to explore more about what GuardianCall.ai can do for you.
              </p>
              <p style="color: #555; font-size: 16px;">Warm regards,<br/>The GuardianCall.ai Team</p>
            </td>
          </tr>
          <tr>
            <td style="background-color: #f0f0f0; text-align: center; padding: 20px;">
              <p style="font-size: 12px; color: #999;">© 2025 GuardianCall.ai. All rights reserved.</p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`
  };

  return transporter.sendMail(mailOptions);
}

// Send signup request to admin + acknowledgment to user
async function sendSignupEmail(email, firstName, lastName, password) {
  if (!canSendEmail(email)) {
    const error = new Error(`Rate limit exceeded for ${email}. Please try again later.`);
    error.status = 429; // Too Many Requests
    throw error;
  }

  const mailOptions = {
    from: `"GuardianCall.ai" <${process.env.GMAIL_USER}>`,
    to: process.env.gmail_admin,
    subject: 'Signup request',
    html: `<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <title>New Signup Request - GuardianCall</title>
</head>
<body style="font-family: Arial, sans-serif; background-color: #f9f9f9;">
  <table width="100%" cellspacing="0" cellpadding="0">
    <tr>
      <td align="center">
        <table width="600" style="background-color: #ffffff; margin-top: 30px; border-radius: 10px;">
          <tr>
            <td align="center" style="padding: 30px;">
              <img src="https://s3.blr.cloudtopiaa.com:6780/swift/v1/AUTH_02a111ba8aca4efcbc139b77a7b37f30/gaurdian-ui/GuardianCallAi-Logo.png" alt="GuardianCall.ai Logo" style="max-width: 250px;" />
            </td>
          </tr>
          <tr>
            <td style="padding: 30px 40px;">
              <h2 style="color: #333;">New Signup Request Received</h2>
              <p style="color: #555; font-size: 16px;">Hi Admin,</p>
              <p style="color: #555; font-size: 16px;">A new user has requested signup on GuardianCall.ai.</p>
              <h3 style="color: #333;">User Details:</h3>
              <ul style="color: #555; font-size: 16px; list-style: none; padding-left: 0;">
                <li><strong>First Name:</strong> ${firstName}</li>
                <li><strong>Last Name:</strong> ${lastName}</li>
                <li><strong>Email:</strong> ${email}</li>
                <li><strong>Suggested Password:</strong> ${password}</li>
              </ul>
              <p style="color: #555; font-size: 16px;">Please verify the information and take appropriate action.</p>
              <p style="color: #555; font-size: 16px;">Cheers,<br/>The GuardianCall.ai Team</p>
            </td>
          </tr>
          <tr>
            <td style="background-color: #f0f0f0; text-align: center; padding: 20px;">
              <p style="font-size: 12px; color: #999;">© 2025 GuardianCall.ai. All rights reserved.</p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`
  };

  // Send both emails
  await sendAcknowledgementEmail(firstName, email);
  return transporter.sendMail(mailOptions);
}



module.exports = { sendSignupEmail };
