import nodemailer from 'nodemailer';
import dotenv from 'dotenv';
import ejs from 'ejs';
import path from 'path';
import { DateFormatter } from './dateFormatter';
import { humanizeClientError } from './humanReadableError';

dotenv.config();

export class EmailService {
  private transporter;

  constructor() {
    this.transporter = nodemailer.createTransport({
      host: process.env.EMAIL_HOST!,
      port: parseInt(process.env.MAIL_PORT!),
      secure: process.env.EMAIL_SECURE === 'true' || process.env.MAIL_PORT === '465',

      auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS,
      },
      tls: {
        rejectUnauthorized: false, // Often needed for private mail servers
      },
    });
  }

  // Check if email service is properly configured
  private isConfigured(): boolean {
    return (
      !!process.env.EMAIL_HOST &&
      !!process.env.MAIL_PORT &&
      !!process.env.EMAIL_USER &&
      !!process.env.EMAIL_PASS
    );
  }

  // Verify email configuration
  public async verifyConnection(): Promise<boolean> {
    if (!this.isConfigured()) {
      console.warn(
        'Email service is not properly configured. Missing environment variables.'
      );
      return false;
    }

    try {
      await this.transporter.verify();
      console.log('Email service is ready');
      return true;
    } catch (error) {
      console.error('Email service error:', error);
      return false;
    }
  }

  // Generate OTP email template
  private generateOtpTemplate(otp: string, recipientName?: string): string {
    const greeting = recipientName ? `Hi ${recipientName},` : 'Hello,';

    return `<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Your OTP Code</title>
    <style>
      @media only screen and (max-width: 600px) {
        .container {
          width: 100% !important;
        }
        .content-padding {
          padding: 20px !important;
        }
        .otp-container {
          width: 90% !important;
          max-width: 250px !important;
        }
        .header-padding {
          padding: 20px !important;
        }
        .footer-padding {
          padding: 20px !important;
        }
        .otp-code {
          font-size: 28px !important;
          letter-spacing: 3px !important;
        }
      }
    </style>
  </head>
  <body
    style="
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f0f9ff;
    "
  >
    <table
      role="presentation"
      cellspacing="0"
      cellpadding="0"
      border="0"
      width="100%"
      style="background-color: #f0f9ff"
    >
      <tr>
        <td style="padding: 20px 0">
          <table
            role="presentation"
            cellspacing="0"
            cellpadding="0"
            border="0"
            width="600"
            align="center"
            class="container"
            style="
              background: white;
              border-radius: 16px;
              box-shadow: 0 10px 40px rgba(0, 0, 0, 0.08);
              overflow: hidden;
            "
          >
            <!-- Header -->
            <tr>
              <td
                style="
                  background: #4f46e5;
                  padding: 30px 40px;
                  text-align: center;
                  color: white;
                  position: relative;
                "
                class="header-padding"
              >
                <table
                  role="presentation"
                  cellspacing="0"
                  cellpadding="0"
                  border="0"
                  width="100%"
                >
                  <tr>
                    <td style="text-align: center; position: relative">
                      <p
                        style="
                          font-size: 24px;
                          color: white;
                          font-weight: 700;
                          margin: 0 0 8px 0;
                          display: flex;
                          align-items: center;
                          justify-content: center;
                          gap: 10px;
                          animation: float 3s ease-in-out infinite;
                        "
                      >
                        <span style="font-size: 28px">🚀</span> QuickConnect
                      </p>
                      <h1
                        style="
                          font-size: 20px;
                          font-weight: 600;
                          margin: 0;
                          opacity: 0.95;
                          color: white;
                        "
                      >
                        Account Verification
                      </h1>
                    </td>
                  </tr>
                </table>
              </td>
            </tr>

            <!-- Content -->
            <tr>
              <td style="padding: 40px" class="content-padding">
                <table
                  role="presentation"
                  cellspacing="0"
                  cellpadding="0"
                  border="0"
                  width="100%"
                >
                  <tr>
                    <td>
                      <p
                        style="
                          font-size: 18px;
                          color: #1f2937;
                          margin: 0 0 20px 0;
                          font-weight: 500;
                        "
                      >
                        ${greeting}
                      </p>

                      <p
                        style="
                          font-size: 16px;
                          color: #6b7280;
                          margin: 0 0 30px 0;
                          line-height: 1.7;
                        "
                      >
                        You have requested a verification code for your QuickConnect
                        account. Please use the code below to complete your verification
                        process.
                      </p>

                      <table
                        role="presentation"
                        cellspacing="0"
                        cellpadding="0"
                        border="0"
                        width="100%"
                      >
                        <tr>
                          <td style="text-align: center; padding: 0 20px">
                            <div
                              style="
                                font-size: 14px;
                                color: #6b7280;
                                text-transform: uppercase;
                                letter-spacing: 1px;
                                margin-bottom: 12px;
                                font-weight: 600;
                              "
                            >
                              Your Verification Code
                            </div>
                            <table
                              role="presentation"
                              cellspacing="0"
                              cellpadding="0"
                              border="0"
                              align="center"
                              style="
                                background: #6366f1;
                                padding: 35px 20px;
                                border-radius: 16px;
                                position: relative;
                                overflow: hidden;
                                width: 100%;
                                max-width: 300px;
                              "
                            >
                              <tr>
                                <td style="position: relative; text-align: center">
                                  <div
                                    style="
                                      font-size: 32px;
                                      font-weight: 700;
                                      color: white;
                                      letter-spacing: 6px;
                                      margin: 0 auto 15px auto;
                                      position: relative;
                                      z-index: 1;
                                      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
                                      display: block;
                                    "
                                  >
                                    ${otp}
                                  </div>
                                  <div
                                    style="
                                      font-size: 14px;
                                      color: rgba(255, 255, 255, 0.8);
                                      margin: 0 auto;
                                      font-weight: 500;
                                      display: block;
                                    "
                                  >
                                    Expires in 10 minutes
                                  </div>
                                </td>
                              </tr>
                            </table>
                          </td>
                        </tr>
                      </table>

                      <table
                        role="presentation"
                        cellspacing="0"
                        cellpadding="0"
                        border="0"
                        width="100%"
                      >
                        <tr>
                          <td style="text-align: center; padding: 30px 0">
                            <a
                              href="#"
                              style="
                                display: inline-block;
                                background: #4f46e5;
                                color: white;
                                text-decoration: none;
                                padding: 14px 32px;
                                border-radius: 50px;
                                font-weight: 600;
                                font-size: 16px;
                                box-shadow: 0 4px 15px rgba(79, 70, 229, 0.3);
                              "
                              >Need Help?</a
                            >
                          </td>
                        </tr>
                      </table>

                      <p
                        style="
                          font-size: 16px;
                          color: #6b7280;
                          margin: 0 0 0 0;
                          line-height: 1.7;
                        "
                      >
                        If you didn't request this code, please ignore this email or
                        contact our support team if you have concerns about your account
                        security.
                      </p>
                    </td>
                  </tr>
                </table>
              </td>
            </tr>

            <!-- Footer -->
            <tr>
              <td
                style="
                  background: #f9fafb;
                  padding: 30px 40px;
                  text-align: center;
                  border-top: 1px solid #e5e7eb;
                "
                class="footer-padding"
              >
                <table
                  role="presentation"
                  cellspacing="0"
                  cellpadding="0"
                  border="0"
                  width="100%"
                >
                  <tr>
                    <td>
                      <p
                        style="
                          color: #6b7280;
                          font-size: 14px;
                          margin: 0 0 15px 0;
                          line-height: 1.6;
                        "
                      >
                        This is an automated message from QuickConnect. Please do not
                        reply to this email.
                      </p>
                      <p
                        style="
                          color: #9ca3af;
                          font-size: 12px;
                          margin: 0;
                          padding-top: 15px;
                          border-top: 1px solid #e5e7eb;
                        "
                      >
                        &copy; ${new Date().getFullYear()} QuickConnect. All rights reserved.
                      </p>
                    </td>
                  </tr>
                </table>
              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
  </body>
</html>`;
  }

  // Send OTP email
  public async sendOtpEmail(
    email: string,
    otp: string,
    recipientName?: string
  ): Promise<{ success: boolean; message: string }> {
    try {
      const mailOptions = {
        from: {
          name: process.env.MAIL_FROM_NAME || 'QuickConnect',
          address:
            process.env.EMAIL_FROM ||
            process.env.EMAIL_USER ||
            'noreply@quickconnect.com',
        },
        to: email,
        subject: `Your QuickConnect Verification Code: ${otp}`,
        html: this.generateOtpTemplate(otp, recipientName),
        text: `Your QuickConnect verification code is: ${otp}. This code will expire in 10 minutes. Don't share this code with anyone.`,
      };

      console.log(`========= MAIL OPTIONS ================`);
      console.log(mailOptions);
      console.log('OTP:', otp);
      console.log('Recipient Name:', recipientName);
      console.log(`========= MAIL OPTIONS ================`);

      console.log('🔌 Testing SMTP connection...');
      // await this.transporter.verify();
      console.log('✅ SMTP connection successful');
      console.log('this.transporter :>> ', this.transporter);
      const info = await this.transporter.sendMail(mailOptions);

      console.log('Email sent successfully:', info.messageId);

      return {
        success: true,
        message: 'OTP email sent successfully',
      };
    } catch (error: any) {
      console.error('Email sending error:', error);
      return {
        success: false,
        message: humanizeClientError(
          error,
          'We could not send the verification email. Please try again.'
        ),
      };
    }
  }

  // Send welcome email (bonus feature)
  public async sendWelcomeEmail(
    email: string,
    name: string
  ): Promise<{ success: boolean; message: string }> {
    // Check if email service is properly configured
    if (!this.isConfigured()) {
      console.warn(
        'Email service is not properly configured. Missing environment variables.'
      );
      return {
        success: false,
        message: 'Email service is not properly configured',
      };
    }

    try {
      // Path to the welcome email template
      const templatePath = path.join(__dirname, '../templates/emails/welcome.ejs');

      // Render the EJS template
      const html = await ejs.renderFile(templatePath, { name: name || 'User' });

      const mailOptions = {
        from: {
          name: process.env.MAIL_FROM_NAME || 'QuickConnect',
          address:
            process.env.EMAIL_FROM ||
            process.env.EMAIL_USER ||
            'noreply@quickconnect.com',
        },
        to: email,
        subject: 'Welcome to QuickConnect! 🎉',
        html: html,
        text: `Hi ${name || 'User'}, Welcome to QuickConnect! Your account has been successfully created and verified. You can now start connecting with others and exploring all the features QuickConnect has to offer.`,
      };

      const info = await this.transporter.sendMail(mailOptions);

      console.log('Welcome email sent successfully:', info.messageId);

      return {
        success: true,
        message: 'Welcome email sent successfully',
      };
    } catch (error: any) {
      console.error('Welcome email sending error:', error);
      return {
        success: false,
        message: humanizeClientError(
          error,
          'We could not send the welcome email. Please try again.'
        ),
      };
    }
  }

  // Generate scan notification email template
  private generateScanNotificationTemplate(scanDetails: {
    recipientName?: string;
    scannedAt: string;
    location?: string;
    deviceInfo?: string;
    qrCodeName?: string;
  }): string {
    const { recipientName, scannedAt, location, qrCodeName } = scanDetails;

    // Format the date and time using DateFormatter
    const formattedDateTime = DateFormatter.formatDateTime(scannedAt);
    const greeting = recipientName ? `Hi ${recipientName},` : 'Hello,';

    return `<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>QR Code Scan Notification</title>
    <style>
      @media only screen and (max-width: 600px) {
        .container {
          width: 100% !important;
        }
        .content-padding {
          padding: 20px !important;
        }
        .header-padding {
          padding: 25px 20px !important;
        }
        .greeting {
          font-size: 16px !important;
        }
        .intro-text {
          font-size: 15px !important;
        }
        .detail-label {
          min-width: 120px !important;
        }
      }
    </style>
  </head>
  <body
    style="
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f0f9ff;
    "
  >
    <table
      role="presentation"
      cellspacing="0"
      cellpadding="0"
      border="0"
      width="100%"
      style="background-color: #f0f9ff"
    >
      <tr>
        <td style="padding: 20px 0">
          <table
            role="presentation"
            cellspacing="0"
            cellpadding="0"
            border="0"
            width="600"
            align="center"
            class="container"
            style="
              background: white;
              border-radius: 16px;
              box-shadow: 0 10px 40px rgba(0, 0, 0, 0.08);
              overflow: hidden;
            "
          >
            <!-- Header -->
            <tr>
              <td
                style="
                  background: #4f46e5;
                  padding: 35px 40px;
                  text-align: center;
                  color: white;
                  position: relative;
                "
                class="header-padding"
              >
                <table
                  role="presentation"
                  cellspacing="0"
                  cellpadding="0"
                  border="0"
                  width="100%"
                >
                  <tr>
                    <td style="text-align: center">
                      <p
                        style="
                          font-size: 24px;
                          color: white;
                          font-weight: 700;
                          margin: 0 0 8px 0;
                          display: flex;
                          align-items: center;
                          justify-content: center;
                          gap: 10px;
                        "
                      >
                        <span style="font-size: 28px">🚀</span> QuickConnect
                      </p>
                      <h1
                        style="
                          font-size: 24px;
                          font-weight: 600;
                          margin: 0 0 8px 0;
                          opacity: 0.95;
                          color: white;
                        "
                      >
                        QR Code Activity Alert
                      </h1>
                      <p
                        style="
                          font-size: 16px;
                          opacity: 0.9;
                          margin: 0;
                          font-weight: 400;
                          color: white;
                        "
                      >
                        Your QR code was successfully scanned
                      </p>
                    </td>
                  </tr>
                </table>
              </td>
            </tr>

            <!-- Content -->
            <tr>
              <td style="padding: 40px" class="content-padding">
                <table
                  role="presentation"
                  cellspacing="0"
                  cellpadding="0"
                  border="0"
                  width="100%"
                >
                  <tr>
                    <td>
                      <p
                        style="
                          font-size: 18px;
                          color: #1f2937;
                          margin: 0 0 20px 0;
                          font-weight: 500;
                        "
                      >
                        ${greeting}
                      </p>

                      <p
                        style="
                          font-size: 16px;
                          color: #6b7280;
                          margin: 0 0 30px 0;
                          line-height: 1.7;
                        "
                      >
                        We're letting you know that someone has just scanned your
                        QuickConnect QR code. Here are the details of this scan event:
                      </p>

                      <table
                        role="presentation"
                        cellspacing="0"
                        cellpadding="0"
                        border="0"
                        width="100%"
                      >
                        <tr>
                          <td
                            style="
                              background: #10b981;
                              padding: 30px;
                              border-radius: 16px;
                              text-align: center;
                              color: white;
                              position: relative;
                            "
                          >
                            <div
                              style="
                                font-size: 48px;
                                margin: 0 0 15px 0;
                                position: relative;
                                z-index: 1;
                              "
                            >
                              📱
                            </div>
                            <p
                              style="
                                font-size: 22px;
                                font-weight: 600;
                                margin: 0 0 10px 0;
                                position: relative;
                                z-index: 1;
                              "
                            >
                              Scan Successful!
                            </p>
                            <p
                              style="
                                font-size: 16px;
                                opacity: 0.9;
                                margin: 0;
                                position: relative;
                                z-index: 1;
                              "
                            >
                              Your QR code was successfully scanned by another user
                            </p>
                          </td>
                        </tr>
                      </table>

                      <table
                        role="presentation"
                        cellspacing="0"
                        cellpadding="0"
                        border="0"
                        width="100%"
                        style="
                          background: #f9fafb;
                          border-radius: 16px;
                          padding: 30px;
                          margin: 30px 0;
                          border: 1px solid #e5e7eb;
                        "
                      >
                        <tr>
                          <td>
                            <h3
                              style="
                                font-size: 18px;
                                color: #1f2937;
                                margin: 0 0 20px 0;
                                font-weight: 600;
                                display: flex;
                                align-items: center;
                                gap: 10px;
                              "
                            >
                              📋 Scan Details
                            </h3>

                            <table
                              role="presentation"
                              cellspacing="0"
                              cellpadding="0"
                              border="0"
                              width="100%"
                            >
                              ${
                                qrCodeName
                                  ? `<tr>
                                <td
                                  style="
                                    display: flex;
                                    padding: 15px 0;
                                    border-bottom: 1px solid #e5e7eb;
                                    align-items: flex-start;
                                  "
                                >
                                  <span
                                    style="
                                      font-weight: 600;
                                      color: #4b5563;
                                      min-width: 140px;
                                      flex-shrink: 0;
                                    "
                                    >🏷️ QR Code:</span
                                  >
                                  <span
                                    style="
                                      color: #1f2937;
                                      flex: 1;
                                      word-break: break-word;
                                      line-height: 1.5;
                                    "
                                    >${qrCodeName}</span
                                  >
                                </td>
                              </tr>`
                                  : ''
                              }
                              <tr>
                                <td
                                  style="
                                    display: flex;
                                    padding: 15px 0;
                                    border-bottom: 1px solid #e5e7eb;
                                    align-items: flex-start;
                                  "
                                >
                                  <span
                                    style="
                                      font-weight: 600;
                                      color: #4b5563;
                                      min-width: 140px;
                                      flex-shrink: 0;
                                    "
                                    >🕐 Date & Time:</span
                                  >
                                  <span
                                    style="
                                      color: #1f2937;
                                      flex: 1;
                                      word-break: break-word;
                                      line-height: 1.5;
                                    "
                                    >${formattedDateTime}</span
                                  >
                                </td>
                              </tr>
                              ${
                                location
                                  ? `<tr>
                                <td
                                  style="
                                    display: flex;
                                    padding: 15px 0;
                                    align-items: flex-start;
                                  "
                                >
                                  <span
                                    style="
                                      font-weight: 600;
                                      color: #4b5563;
                                      min-width: 140px;
                                      flex-shrink: 0;
                                    "
                                    >📍 Location:</span
                                  >
                                  <span
                                    style="
                                      color: #1f2937;
                                      flex: 1;
                                      word-break: break-word;
                                      line-height: 1.5;
                                    "
                                    >${location}</span
                                  >
                                </td>
                              </tr>`
                                  : ''
                              }
                            </table>
                          </td>
                        </tr>
                      </table>

                      <table
                        role="presentation"
                        cellspacing="0"
                        cellpadding="0"
                        border="0"
                        width="100%"
                      >
                        <tr>
                          <td
                            style="
                              background: #fef3c7;
                              border: 1px solid #fbbf24;
                              border-radius: 16px;
                              padding: 20px;
                              margin: 30px 0;
                              text-align: center;
                            "
                          >
                            <div
                              style="
                                font-size: 16px;
                                font-weight: 600;
                                color: #92400e;
                                margin: 0 0 8px 0;
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                gap: 8px;
                              "
                            >
                              ⚠️ Security Notice
                            </div>
                            <p
                              style="
                                font-size: 14px;
                                color: #9d390a;
                                margin: 0;
                                line-height: 1.6;
                              "
                            >
                              Remember to only share your QR codes with trusted
                              contacts. If you did not authorize this scan, please
                              secure your account.
                            </p>
                          </td>
                        </tr>
                      </table>

                      <table
                        role="presentation"
                        cellspacing="0"
                        cellpadding="0"
                        border="0"
                        width="100%"
                      >
                        <tr>
                          <td style="text-align: center; padding: 30px 0">
                            <a
                              href="#"
                              style="
                                display: inline-block;
                                background: #4f46e5;
                                color: white;
                                text-decoration: none;
                                padding: 14px 32px;
                                border-radius: 50px;
                                font-weight: 600;
                                font-size: 16px;
                                box-shadow: 0 4px 15px rgba(79, 70, 229, 0.3);
                              "
                              >View Activity</a
                            >
                          </td>
                        </tr>
                      </table>

                      <p
                        style="
                          font-size: 16px;
                          color: #6b7280;
                          margin: 0 0 0 0;
                          line-height: 1.7;
                        "
                      >
                        You're receiving this notification because of your account
                        activity settings. You can adjust your notification preferences
                        in your account settings.
                      </p>
                    </td>
                  </tr>
                </table>
              </td>
            </tr>

            <!-- Footer -->
            <tr>
              <td
                style="
                  background: #f9fafb;
                  padding: 30px 40px;
                  text-align: center;
                  border-top: 1px solid #e5e7eb;
                "
              >
                <table
                  role="presentation"
                  cellspacing="0"
                  cellpadding="0"
                  border="0"
                  width="100%"
                >
                  <tr>
                    <td>
                      <p
                        style="
                          color: #6b7280;
                          font-size: 14px;
                          margin: 0 0 15px 0;
                          line-height: 1.6;
                        "
                      >
                        Questions? Our support team is here to help you with any
                        concerns.
                      </p>
                      <table
                        role="presentation"
                        cellspacing="0"
                        cellpadding="0"
                        border="0"
                        width="100%"
                      >
                        <tr>
                          <td style="text-align: center">
                            <a
                              href="#"
                              style="
                                color: #4f46e5;
                                text-decoration: none;
                                font-size: 13px;
                                padding: 0 10px;
                              "
                              >Help Center</a
                            >
                            <a
                              href="#"
                              style="
                                color: #4f46e5;
                                text-decoration: none;
                                font-size: 13px;
                                padding: 0 10px;
                              "
                              >Security</a
                            >
                            <a
                              href="#"
                              style="
                                color: #4f46e5;
                                text-decoration: none;
                                font-size: 13px;
                                padding: 0 10px;
                              "
                              >Privacy Policy</a
                            >
                          </td>
                        </tr>
                      </table>
                      <p
                        style="
                          color: #6b7280;
                          font-size: 14px;
                          margin: 15px 0 15px 0;
                          line-height: 1.6;
                        "
                      >
                        This is an automated notification from QuickConnect. Please do
                        not reply to this email.
                      </p>
                      <p
                        style="
                          color: #9ca3af;
                          font-size: 12px;
                          margin: 0;
                          padding-top: 15px;
                          border-top: 1px solid #e5e7eb;
                        "
                      >
                        © 2025 QuickConnect. All rights reserved.
                      </p>
                    </td>
                  </tr>
                </table>
              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
  </body>
</html>`;
  }

  // ====== SMTP CREDENTIAL TESTING FUNCTION ==============
  public async testSMTPCredentials(testEmail?: string): Promise<{
    success: boolean;
    message: string;
    details?: any;
    configStatus?: any;
  }> {
    const testRecipient = testEmail || process.env.EMAIL_USER || 'test@example.com';

    try {
      // Step 1: Check configuration
      const configStatus = {
        EMAIL_HOST: !!process.env.EMAIL_HOST,
        MAIL_PORT: !!process.env.MAIL_PORT,
        EMAIL_USER: !!process.env.EMAIL_USER,
        EMAIL_PASS: !!process.env.EMAIL_PASS,
        EMAIL_FROM: !!process.env.EMAIL_FROM,
      };

      console.log('🔧 SMTP Configuration Status:', configStatus);

      if (!this.isConfigured()) {
        return {
          success: false,
          message: 'SMTP configuration is incomplete',
          configStatus,
        };
      }

      // Step 2: Test connection
      console.log('🔌 Testing SMTP connection...');
      await this.transporter.verify();
      console.log('✅ SMTP connection successful');

      // Step 3: Send test email
      console.log('📧 Sending test email...');

      const message = {
        from: {
          name: process.env.MAIL_FROM_NAME || 'QuickConnect',
          address: process.env.EMAIL_FROM || process.env.EMAIL_USER || '',
        },
        to: testRecipient,
        subject: '✅ SMTP Test - QuickConnect Email Service',
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <h2 style="color: #4CAF50;">✅ SMTP Test Successful!</h2>
            <p>This is a test email to verify your SMTP configuration is working correctly.</p>

            <div style="background: #f5f5f5; padding: 15px; border-radius: 5px; margin: 20px 0;">
              <h3>Configuration Details:</h3>
              <ul>
                <li><strong>Host:</strong> ${process.env.EMAIL_HOST}</li>
                <li><strong>Port:</strong> ${process.env.MAIL_PORT}</li>
                <li><strong>User:</strong> ${process.env.EMAIL_USER}</li>
                <li><strong>From:</strong> ${process.env.EMAIL_FROM}</li>
                <li><strong>Secure:</strong> ${parseInt(process.env.MAIL_PORT || '587') === 465 ? 'SSL' : 'TLS'}</li>
              </ul>
            </div>

            <p style="color: #666;">
              <small>Test sent at: ${new Date().toISOString()}</small>
            </p>
          </div>
        `,
        text: `SMTP Test Successful! Your email configuration is working correctly. Test sent at: ${new Date().toISOString()}`,
      };

      const info = await this.transporter.sendMail(message);

      console.log('✅ Test email sent successfully:', info.messageId);

      return {
        success: true,
        message: `Test email sent successfully to ${testRecipient}`,
        details: {
          messageId: info.messageId,
          response: info.response,
          envelope: info.envelope,
        },
        configStatus,
      };
    } catch (error: any) {
      console.error('❌ SMTP test failed:', error);

      return {
        success: false,
        message: humanizeClientError(
          error,
          'The email test failed. Please check your mail server settings and try again.'
        ),
        details: {
          code: error.code,
          command: error.command,
          response: error.response,
          responseCode: error.responseCode,
        },
        configStatus: {
          EMAIL_HOST: !!process.env.EMAIL_HOST,
          MAIL_PORT: !!process.env.MAIL_PORT,
          EMAIL_USER: !!process.env.EMAIL_USER,
          EMAIL_PASS: !!process.env.EMAIL_PASS,
          EMAIL_FROM: !!process.env.EMAIL_FROM,
        },
      };
    }
  }

  // ====== SEND SCAN EMAIL ==============
  public async SendScanEmail(
    email: string,
    scanDetails: {
      recipientName?: string;
      scannedAt: string;
      location?: string;
      deviceInfo?: string;
      qrCodeName?: string;
    }
  ): Promise<{ success: boolean; message: string }> {
    // Check if email service is properly configured
    if (!this.isConfigured()) {
      console.warn(
        'Email service is not properly configured. Missing environment variables.'
      );
      return {
        success: false,
        message: 'Email service is not properly configured',
      };
    }

    try {
      console.log(email);
      console.log(scanDetails);

      if (!email || !email.includes('@')) {
        return {
          success: false,
          message: 'Recipient address is missing or invalid',
        };
      }

      const mailOptions = {
        from: {
          name: process.env.MAIL_FROM_NAME || 'QuickConnect',
          address:
            process.env.EMAIL_FROM ||
            process.env.EMAIL_USER ||
            'noreply@quickconnect.com',
        },
        to: email,
        subject: 'QR Code Scan Notification',
        html: this.generateScanNotificationTemplate(scanDetails),
      };

      const info = await this.transporter.sendMail(mailOptions);

      console.log('Scan notification email sent successfully:', info.messageId);

      return {
        success: true,
        message: 'Scan notification email sent successfully',
      };
    } catch (error: any) {
      console.error('Scan notification email error:', error);
      return {
        success: false,
        message: humanizeClientError(
          error,
          'We could not send the scan notification email. Please try again.'
        ),
      };
    }
  }
}
