// utils/emailService.js
import nodemailer from 'nodemailer';


const COMPANY_NAME = "HireLoom Global Staffing Solution";
const FRONTEND_URL = "https://hireloomglobal.com";
const LOGO_URL     = "https://hireloomglobal.com/images/hl_logo.png";
const SMTP_USER    = "support@hireloomglobal.com";
const SMTP_PASS    = "Hireloom##26";
const MAIL_FROM    = `"${COMPANY_NAME}" <${SMTP_USER}>`;   // ✅ closing > was missing before



const transporter = nodemailer.createTransport({
  host      : "mail.hireloomglobal.com",
  port      : 465,
  secure    : true,
  auth      : {                 
    user: SMTP_USER,
    pass: SMTP_PASS,
  },
  tls: {
    rejectUnauthorized: false,         // ✅ ignore self-signed cert issues on shared hosting
  },
});


const emailHeader = () => `
  <tr>
    <td style="background:linear-gradient(135deg, #f0f7ff 0%, #e0f2ff 60%, #fff3e8 100%);
                padding:36px 40px;text-align:center;">
      <img src="${LOGO_URL}" alt="${COMPANY_NAME}"
           style="height:52px;max-width:220px;object-fit:contain;" />
    </td>
  </tr>`;

const emailFooter = () => `
  <tr>
    <td style="background:#f9fafb;border-top:1px solid #e5e7eb;
                padding:24px 48px;text-align:center;">
      <p style="margin:0 0 6px;font-size:13px;color:#9ca3af;">
        This email was sent by <strong style="color:#6b7280;">${COMPANY_NAME}</strong>
      </p>
      <p style="margin:0;font-size:12px;color:#d1d5db;">
        &copy; ${new Date().getFullYear()} ${COMPANY_NAME}. All rights reserved.
      </p>
    </td>
  </tr>`;

const emailWrapper = (content) => `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body style="margin:0;padding:0;background:#f4f6f9;font-family:'Segoe UI',Arial,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f6f9;padding:40px 0;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0"
               style="background:#ffffff;border-radius:12px;overflow:hidden;
                      box-shadow:0 4px 24px rgba(0,0,0,0.08);max-width:600px;width:100%;">
          ${emailHeader()}
          ${content}
          ${emailFooter()}
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;

// ─────────────────────────────────────────────────────────────
// Template — Password Reset
// ─────────────────────────────────────────────────────────────
const buildResetEmail = ({ name, resetURL, expiryMinutes = 60 }) => emailWrapper(`
  <tr>
    <td style="padding:44px 48px 36px;">
      <p style="margin:0 0 8px;font-size:22px;font-weight:700;color:#1a1a2e;">
        Hello, ${name} 👋
      </p>
      <p style="margin:0 0 28px;font-size:15px;color:#6b7280;line-height:1.6;">
        We received a request to reset the password for your HireLoom account.
        Click the button below to set a new password.
      </p>

      <table width="100%" cellpadding="0" cellspacing="0">
        <tr>
          <td align="center" style="padding:8px 0 32px;">
            <a href="${resetURL}"
               style="display:inline-block;background:linear-gradient(135deg,#f97316,#ea580c);
                      color:#ffffff;font-size:16px;font-weight:700;padding:16px 48px;
                      border-radius:8px;text-decoration:none;letter-spacing:0.4px;">
              Reset My Password
            </a>
          </td>
        </tr>
      </table>

      <hr style="border:none;border-top:1px solid #e5e7eb;margin:0 0 28px;"/>

      <table width="100%" cellpadding="0" cellspacing="0"
             style="background:#fef9ec;border:1px solid #fde68a;border-radius:8px;margin-bottom:28px;">
        <tr>
          <td style="padding:16px 20px;">
            <p style="margin:0;font-size:13px;color:#92400e;line-height:1.6;">
              &#9200; <strong>This link will expire in ${expiryMinutes} minutes.</strong><br/>
              If you did not request a password reset, you can safely ignore this email.
              Your password will not be changed.
            </p>
          </td>
        </tr>
      </table>

      <p style="margin:0 0 6px;font-size:13px;color:#9ca3af;">
        If the button does not work, copy and paste this link into your browser:
      </p>
      <p style="margin:0;font-size:12px;word-break:break-all;">
        <a href="${resetURL}" style="color:#f97316;text-decoration:none;">${resetURL}</a>
      </p>
    </td>
  </tr>`);

// ─────────────────────────────────────────────────────────────
// Template — Welcome + Credentials
// ─────────────────────────────────────────────────────────────
const buildWelcomeEmail = ({ name, email, password, designation, loginURL }) => emailWrapper(`
  <tr>
    <td style="background:linear-gradient(90deg,#f97316,#ea580c);
                padding:20px 48px;text-align:center;">
      <p style="margin:0;font-size:18px;font-weight:800;color:#ffffff;letter-spacing:0.5px;">
        Welcome to ${COMPANY_NAME}!
      </p>
    </td>
  </tr>
  <tr>
    <td style="padding:40px 48px 32px;">
      <p style="margin:0 0 6px;font-size:22px;font-weight:700;color:#1a1a2e;">
        Hello, ${name}! 👋
      </p>
      <p style="margin:0 0 28px;font-size:15px;color:#6b7280;line-height:1.6;">
        Your HireLoom account has been created successfully.
        Here are your login credentials — please keep them safe.
      </p>

      <table width="100%" cellpadding="0" cellspacing="0"
             style="background:#f0f5ff;border:1.5px solid #c7d7f8;border-radius:10px;margin-bottom:28px;">
        <tr>
          <td style="padding:24px 28px;">
            <p style="margin:0 0 16px;font-size:12px;font-weight:800;
                       text-transform:uppercase;letter-spacing:1px;color:#4b5563;">
              Your Login Credentials
            </p>
            <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:12px;">
              <tr>
                <td style="width:90px;font-size:12px;font-weight:700;color:#6b7280;
                           padding:10px 0;vertical-align:top;">Email</td>
                <td style="font-size:14px;font-weight:700;color:#1a1a2e;
                           background:#ffffff;border:1px solid #e5e7eb;
                           border-radius:6px;padding:10px 14px;">${email}</td>
              </tr>
            </table>
            <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:12px;">
              <tr>
                <td style="width:90px;font-size:12px;font-weight:700;color:#6b7280;
                           padding:10px 0;vertical-align:top;">Password</td>
                <td style="font-size:15px;font-weight:800;color:#f97316;
                           background:#ffffff;border:1px solid #e5e7eb;
                           border-radius:6px;padding:10px 14px;
                           letter-spacing:1px;font-family:monospace;">${password}</td>
              </tr>
            </table>
            ${designation ? `
            <table width="100%" cellpadding="0" cellspacing="0">
              <tr>
                <td style="width:90px;font-size:12px;font-weight:700;color:#6b7280;
                           padding:10px 0;vertical-align:top;">Role</td>
                <td style="font-size:13px;font-weight:600;color:#374151;
                           background:#ffffff;border:1px solid #e5e7eb;
                           border-radius:6px;padding:10px 14px;">${designation}</td>
              </tr>
            </table>` : ''}
          </td>
        </tr>
      </table>

      <table width="100%" cellpadding="0" cellspacing="0">
        <tr>
          <td align="center" style="padding:0 0 28px;">
            <a href="${loginURL}"
               style="display:inline-block;background:linear-gradient(135deg,#f97316,#ea580c);
                      color:#ffffff;font-size:15px;font-weight:700;padding:15px 48px;
                      border-radius:8px;text-decoration:none;letter-spacing:0.4px;">
              Login to HireLoom &rarr;
            </a>
          </td>
        </tr>
      </table>

      <hr style="border:none;border-top:1px solid #e5e7eb;margin:0 0 24px;"/>

      <table width="100%" cellpadding="0" cellspacing="0"
             style="background:#fef9ec;border:1px solid #fde68a;border-radius:8px;">
        <tr>
          <td style="padding:14px 18px;">
            <p style="margin:0;font-size:12px;color:#92400e;line-height:1.7;">
              &#9888; <strong>Security tip:</strong> Please change your password after your first login.
              Do not share these credentials with anyone.
            </p>
          </td>
        </tr>
      </table>
    </td>
  </tr>`);

// ─────────────────────────────────────────────────────────────
// sendWelcomeEmail
// ─────────────────────────────────────────────────────────────
export const sendWelcomeEmail = async ({ toEmail, name, password, designation }) => {
  const info = await transporter.sendMail({
    from   : MAIL_FROM,
    to     : toEmail,
    subject: 'Welcome to HireLoom Global — Your Account Details',
    html   : buildWelcomeEmail({
      name, email: toEmail, password, designation,
      loginURL: `${FRONTEND_URL}/login`,
    }),
  });
  console.log(`✅ Welcome email sent → ${toEmail} [${info.messageId}]`);
  return info;
};

// ─────────────────────────────────────────────────────────────
// sendResetEmail
// ─────────────────────────────────────────────────────────────
export const sendResetEmail = async ({ toEmail, name, resetURL, expiryMinutes = 60 }) => {
  const info = await transporter.sendMail({
    from   : MAIL_FROM,
    to     : toEmail,
    subject: 'Reset Your HireLoom Password',
    html   : buildResetEmail({ name, resetURL, expiryMinutes }),
  });
  console.log(`✅ Reset email sent → ${toEmail} [${info.messageId}]`);
  return info;
};

// ─────────────────────────────────────────────────────────────
// verifyConnection — call on server startup to confirm SMTP works
// ─────────────────────────────────────────────────────────────
export const verifyEmailConnection = async () => {
  try {
    await transporter.verify();
    console.log('✅ SMTP connection verified — emails ready');
  } catch (err) {
    console.error('❌ SMTP connection failed:', err.message);
    console.error('   Check: host, port, username, password in emailService.js');
  }
};