
import nodemailer from 'nodemailer';

/**
 * Returns a configured nodemailer transporter using env variables.
 */
export function getTransporter() {
  const EMAIL_HOST = process.env.EMAIL_HOST;
  const EMAIL_PORT = process.env.EMAIL_PORT;
  const EMAIL_USER = process.env.EMAIL_USER;
  const EMAIL_PASSWORD = process.env.EMAIL_PASSWORD;

  if (!EMAIL_HOST || !EMAIL_PORT || !EMAIL_USER || !EMAIL_PASSWORD) {
    throw new Error('Email environment variables (EMAIL_HOST, EMAIL_PORT, EMAIL_USER, EMAIL_PASSWORD) are not set.');
  }

  const port = parseInt(EMAIL_PORT, 10);

  return nodemailer.createTransport({
    host: EMAIL_HOST,
    port,
    secure: port === 465,
    auth: {
      user: EMAIL_USER,
      pass: EMAIL_PASSWORD,
    },
    ...(port === 587 && {
      requireTLS: true,
      tls: { ciphers: 'SSLv3' },
    }),
  });
}

/**
 * Returns the sender address formatted for use in the "from" field.
 */
export function getSender() {
  const EMAIL_SENDER = process.env.EMAIL_SENDER || process.env.EMAIL_USER || '';
  return `"Morox Properties" <${EMAIL_SENDER}>`;
}

/**
 * Wraps email body content in the branded Morox Properties email template.
 */
export function brandedEmailTemplate(bodyContent: string): string {
  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://moroxproperties.co.bw';
  return `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Morox Properties</title>
</head>
<body style="margin: 0; padding: 0; background-color: #f8f8f8; font-family: 'Montserrat', Arial, Helvetica, sans-serif; color: #282828;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color: #f8f8f8;">
    <tr>
      <td align="center" style="padding: 30px 15px;">
        <table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width: 600px; width: 100%; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.08);">

          <!-- Header -->
          <tr>
            <td style="background-color: #0e1d3c; padding: 28px 32px; text-align: center;">
              <h1 style="margin: 0; font-size: 22px; font-weight: 700; color: #ffffff; letter-spacing: 1px;">MOROX PROPERTIES</h1>
              <p style="margin: 4px 0 0; font-size: 12px; color: rgba(255,255,255,0.65); letter-spacing: 0.5px;">Specialists in sourcing the best places to call home</p>
            </td>
          </tr>

          <!-- Body -->
          <tr>
            <td style="padding: 36px 32px 28px;">
              ${bodyContent}
            </td>
          </tr>

          <!-- Divider -->
          <tr>
            <td style="padding: 0 32px;">
              <hr style="border: none; border-top: 1px solid #e5e5e5; margin: 0;" />
            </td>
          </tr>

          <!-- Footer -->
          <tr>
            <td style="padding: 24px 32px 28px; text-align: center;">
              <p style="margin: 0 0 6px; font-size: 12px; color: #888;">Morox Properties (Pty) Ltd</p>
              <p style="margin: 0 0 6px; font-size: 11px; color: #aaa;">Gaborone &bull; Francistown &bull; Maun</p>
              <p style="margin: 0 0 10px; font-size: 11px; color: #aaa;">
                <a href="mailto:info@moroxproperties.co.bw" style="color: #053885; text-decoration: none;">info@moroxproperties.co.bw</a>
                &nbsp;|&nbsp;
                <a href="tel:+2673912098" style="color: #053885; text-decoration: none;">+267 391 2098</a>
              </p>
              <p style="margin: 0; font-size: 11px; color: #bbb;">
                <a href="${siteUrl}" style="color: #053885; text-decoration: none;">moroxproperties.co.bw</a>
              </p>
            </td>
          </tr>

        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
}

/**
 * Sends an email using the branded template.
 */
export async function sendCustomEmail({ to, subject, html }: { to: string; subject: string; html: string }) {
  const transporter = getTransporter();

  const mailOptions = {
    from: getSender(),
    to,
    subject,
    html: brandedEmailTemplate(html),
  };

  try {
    await transporter.sendMail(mailOptions);
    console.log('Email sent successfully to:', to);
  } catch (error) {
    console.error('Error sending email:', error);
    throw new Error('Could not send email.');
  }
}
