// Lazy-load nodemailer to avoid build-time errors when the package is missing
let nodemailer: typeof import('nodemailer') | null = null;
try {
  // eslint-disable-next-line @typescript-eslint/no-require-imports
  nodemailer = require('nodemailer');
} catch {
  // nodemailer not installed — email sending will fall back to console logging
}

// Create reusable transporter
function getTransporter() {
  const host = process.env.SMTP_HOST;
  const port = Number(process.env.SMTP_PORT) || 587;
  const user = process.env.SMTP_USER;
  const pass = process.env.SMTP_PASS;

  if (!nodemailer) return null;
  if (!user || !pass || user === 'your-email@gmail.com' || pass === 'your-app-password') {
    // SMTP not configured — return null so caller can fall back
    return null;
  }

  return nodemailer.createTransport({
    host,
    port,
    secure: port === 465, // true for 465, false for other ports
    auth: { user, pass },
    connectionTimeout: 10_000, // 10s timeout for initial connection
    greetingTimeout: 10_000,  // 10s timeout for SMTP greeting
    socketTimeout: 15_000,    // 15s timeout for inactivity during send
  });
}

/**
 * Translate common SMTP/Gmail errors into friendly, actionable messages.
 */
function interpretSmtpError(rawMessage: string): string {
  const msg = rawMessage.toLowerCase();

  // Gmail auth errors
  if (msg.includes('invalid login') || msg.includes('username and password not accepted') || msg.includes('authentication failed')) {
    return 'SMTP authentication failed. For Gmail, you MUST use an App Password (not your regular password). '
      + 'See .env for instructions on generating one at https://myaccount.google.com/apppasswords';
  }

  // Less secure apps / 2FA errors
  if (msg.includes('less secure') || msg.includes('allow less secure')) {
    return 'Gmail no longer supports "Less Secure Apps". You must use an App Password with 2-Step Verification enabled. '
      + 'Enable 2SV: https://myaccount.google.com/signinoptions/two-step-verification — '
      + 'Then create App Password: https://myaccount.google.com/apppasswords';
  }

  // Connection / network errors
  if (msg.includes('econnrefused') || msg.includes('connect eintr') || msg.includes('connect econnreset')) {
    return `SMTP connection refused. Check SMTP_HOST and SMTP_PORT in .env (current: ${process.env.SMTP_HOST}:${process.env.SMTP_PORT || 587}).`;
  }

  if (msg.includes('etimedout') || msg.includes('timed out') || msg.includes('timeout')) {
    return 'SMTP connection timed out. This could be a network issue or the SMTP server is unreachable.';
  }

  // TLS / SSL errors
  if (msg.includes('ssl') || msg.includes('tls') || msg.includes('certificate')) {
    return 'SMTP TLS/SSL error. Make sure SMTP_PORT is 587 (STARTTLS) or 465 (SSL).';
  }

  // Sender mismatch
  if (msg.includes('sender') && msg.includes('mismatch')) {
    return 'EMAIL_FROM address must match SMTP_USER for Gmail. Update EMAIL_FROM in .env.';
  }

  // Rate limiting
  if (msg.includes('rate limit') || msg.includes('too many') || msg.includes('temporarily rejected')) {
    return 'SMTP rate limit hit. Wait a few minutes before sending more emails.';
  }

  // Fallback: return original message
  return rawMessage;
}

interface SendEmailOptions {
  to: string;
  subject: string;
  html: string;
  text?: string;
}

/**
 * Send an email. Returns `{ success: true }` or `{ success: false, error: string }`.
 *
 * If SMTP is not configured (missing credentials), the function logs the email
 * content to console (for development) and returns `{ success: true, dev: true }`.
 */
export async function sendEmail({ to, subject, html, text }: SendEmailOptions): Promise<{ success: boolean; error?: string; dev?: boolean }> {
  const transporter = getTransporter();
  const from = process.env.EMAIL_FROM || '"Needyfy" <noreply@needyfy.com>';

  // ── Dev / No-SMTP fallback: log to console ──
  if (!transporter) {
    console.log('──────────────────────────────────────────────');
    console.log('📧 EMAIL NOT SENT (SMTP not configured)');
    console.log(`   To: ${to}`);
    console.log(`   Subject: ${subject}`);
    console.log(`   Body: ${text || html.replace(/<[^>]*>/g, '')}`);
    console.log('──────────────────────────────────────────────');

    return { success: true, dev: true };
  }

  // ── Production: send via SMTP ──
  try {
    const info = await transporter.sendMail({
      from,
      to,
      subject,
      text: text || html.replace(/<[^>]*>/g, ''),
      html,
    });

    console.log(`✅ Email sent to ${to}: ${info.messageId}`);
    return { success: true };
  } catch (error: any) {
    const rawMsg = error?.message || String(error);
    const friendlyError = interpretSmtpError(rawMsg);
    console.error('❌ Email send error:', friendlyError);
    return { success: false, error: friendlyError };
  }
}

/**
 * Send a verification code email with a professional HTML template.
 */
export async function sendVerificationCodeEmail(
  to: string,
  code: string,
  appName: string = 'Needyfy'
): Promise<{ success: boolean; error?: string; dev?: boolean }> {
  const subject = `${appName} — Your Verification Code`;
  const textBody = `Your verification code is: ${code}. This code expires in 10 minutes.`;

  const htmlBody = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${appName} Verification Code</title>
</head>
<body style="margin:0;padding:0;background:#f5f5f5;font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f5f5f5;padding:20px 0;">
    <tr>
      <td align="center">
        <table role="presentation" width="400" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:16px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.08);">
          <!-- Header -->
          <tr>
            <td style="background:linear-gradient(135deg,#f97316,#ea580c);padding:30px 24px;text-align:center;">
              <h1 style="margin:0;color:#ffffff;font-size:24px;font-weight:700;letter-spacing:-0.5px;">${appName}</h1>
              <p style="margin:6px 0 0;color:rgba(255,255,255,0.85);font-size:13px;">Verification Code</p>
            </td>
          </tr>
          <!-- Body -->
          <tr>
            <td style="padding:32px 24px;">
              <p style="margin:0 0 8px;color:#333;font-size:15px;">Hello,</p>
              <p style="margin:0 0 24px;color:#555;font-size:14px;line-height:1.5;">
                You requested a verification code to reset your password. Use the code below to continue:
              </p>
              <!-- Code Box -->
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td align="center">
                    <div style="display:inline-block;background:#fff7ed;border:2px dashed #f97316;border-radius:12px;padding:16px 40px;">
                      <span style="font-size:32px;font-weight:800;color:#ea580c;letter-spacing:8px;font-family:'Courier New',monospace;">${code}</span>
                    </div>
                  </td>
                </tr>
              </table>
              <p style="margin:24px 0 0;color:#888;font-size:12px;text-align:center;">
                ⏱ This code expires in <strong>10 minutes</strong>.
              </p>
              <p style="margin:12px 0 0;color:#999;font-size:12px;text-align:center;">
                If you didn't request this code, you can safely ignore this email.
              </p>
            </td>
          </tr>
          <!-- Footer -->
          <tr>
            <td style="background:#fafafa;padding:16px 24px;border-top:1px solid #eee;">
              <p style="margin:0;color:#aaa;font-size:11px;text-align:center;">
                © ${new Date().getFullYear()} ${appName}. This is an automated message, please do not reply.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;

  return sendEmail({ to, subject, html: htmlBody, text: textBody });
}

/**
 * Check if SMTP is properly configured.
 */
export function isSmtpConfigured(): boolean {
  if (!nodemailer) return false;
  const user = process.env.SMTP_USER;
  const pass = process.env.SMTP_PASS;
  return !!(user && pass && user !== 'your-email@gmail.com' && pass !== 'your-app-password');
}
