const nodemailer = require('nodemailer');

function createTransporter() {
  return nodemailer.createTransport({
    host: process.env.SMTP_HOST || 'smtp.gmail.com',
    port: parseInt(process.env.SMTP_PORT) || 587,
    secure: process.env.SMTP_SECURE === 'true',
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS
    }
  });
}

const FROM = process.env.EMAIL_FROM || 'Layerfive Calibration <noreply@layerfiveltd.com>';
const APP_URL = process.env.APP_URL || 'http://localhost:3000';

async function sendApprovalNotification(user) {
  if (!process.env.SMTP_USER) return;
  const t = createTransporter();
  await t.sendMail({
    from: FROM,
    to: user.email,
    subject: 'Account Approved – Layerfive Calibration System',
    html: `
      <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
        <div style="background:#0d1b3e;padding:20px;text-align:center">
          <h2 style="color:#fff;margin:0">Layerfive Ltd</h2>
          <p style="color:#f97316;margin:5px 0">Calibration Certificate System</p>
        </div>
        <div style="padding:30px;background:#fff;border:1px solid #e5e7eb">
          <h3>Hello ${user.full_name},</h3>
          <p>Your account has been <strong>approved</strong> by the administrator.</p>
          <p>You can now log in to the Layerfive Calibration System.</p>
          <a href="${APP_URL}/login.html" style="display:inline-block;background:#f97316;color:#fff;padding:12px 24px;text-decoration:none;border-radius:6px;margin:20px 0">Login Now</a>
        </div>
        <div style="background:#f3f4f6;padding:15px;text-align:center;font-size:12px;color:#6b7280">
          Layerfive Ltd | 28B Flaming Avenue, Rumuomasi, Port Harcourt
        </div>
      </div>
    `
  });
}

async function sendNewUserNotification(adminEmail, user) {
  if (!process.env.SMTP_USER) return;
  const t = createTransporter();
  await t.sendMail({
    from: FROM,
    to: adminEmail,
    subject: 'New User Registration – Pending Approval',
    html: `
      <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
        <div style="background:#0d1b3e;padding:20px;text-align:center">
          <h2 style="color:#fff;margin:0">Layerfive Ltd</h2>
        </div>
        <div style="padding:30px;background:#fff;border:1px solid #e5e7eb">
          <h3>New Registration Pending Approval</h3>
          <p><strong>Name:</strong> ${user.full_name}</p>
          <p><strong>Email:</strong> ${user.email}</p>
          <p><strong>Department:</strong> ${user.department}</p>
          <a href="${APP_URL}/admin.html" style="display:inline-block;background:#0d1b3e;color:#fff;padding:12px 24px;text-decoration:none;border-radius:6px;margin:20px 0">Review in Admin Panel</a>
        </div>
      </div>
    `
  });
}

async function sendPasswordResetEmail(user, token) {
  if (!process.env.SMTP_USER) return;
  const t = createTransporter();
  const resetUrl = `${APP_URL}/reset-password.html?token=${token}`;
  await t.sendMail({
    from: FROM,
    to: user.email,
    subject: 'Password Reset Request – Layerfive Calibration System',
    html: `
      <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
        <div style="background:#0d1b3e;padding:20px;text-align:center">
          <h2 style="color:#fff;margin:0">Layerfive Ltd</h2>
        </div>
        <div style="padding:30px;background:#fff;border:1px solid #e5e7eb">
          <h3>Password Reset Request</h3>
          <p>Hello ${user.full_name}, you requested a password reset.</p>
          <p>Click the button below. This link expires in <strong>1 hour</strong>.</p>
          <a href="${resetUrl}" style="display:inline-block;background:#f97316;color:#fff;padding:12px 24px;text-decoration:none;border-radius:6px;margin:20px 0">Reset Password</a>
          <p style="font-size:12px;color:#6b7280">If you did not request this, ignore this email.</p>
        </div>
      </div>
    `
  });
}

async function sendExpiryNotification(userEmail, userName, certificates) {
  if (!process.env.SMTP_USER) return;
  const t = createTransporter();
  const rows = certificates.map(c =>
    `<tr><td style="padding:8px;border:1px solid #e5e7eb">${c.certificate_number}</td>
     <td style="padding:8px;border:1px solid #e5e7eb">${c.client}</td>
     <td style="padding:8px;border:1px solid #e5e7eb;color:#dc2626">${c.next_due_date}</td></tr>`
  ).join('');
  await t.sendMail({
    from: FROM,
    to: userEmail,
    subject: 'Calibration Certificate Expiry Alert – Action Required',
    html: `
      <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
        <div style="background:#0d1b3e;padding:20px;text-align:center">
          <h2 style="color:#fff;margin:0">Layerfive Ltd</h2>
          <p style="color:#f97316;margin:5px 0">Expiry Alert</p>
        </div>
        <div style="padding:30px;background:#fff;border:1px solid #e5e7eb">
          <h3>Hello ${userName},</h3>
          <p>The following calibration certificates are expiring within <strong>30 days</strong>:</p>
          <table style="width:100%;border-collapse:collapse;margin:15px 0">
            <thead><tr style="background:#0d1b3e;color:#fff">
              <th style="padding:10px;text-align:left">Certificate No.</th>
              <th style="padding:10px;text-align:left">Client</th>
              <th style="padding:10px;text-align:left">Due Date</th>
            </tr></thead>
            <tbody>${rows}</tbody>
          </table>
          <a href="${APP_URL}/dashboard.html" style="display:inline-block;background:#f97316;color:#fff;padding:12px 24px;text-decoration:none;border-radius:6px">View Dashboard</a>
        </div>
      </div>
    `
  });
}

async function sendSuspensionEmail(user) {
  if (!process.env.SMTP_USER) return;
  const t = createTransporter();
  await t.sendMail({
    from: FROM,
    to: user.email,
    subject: 'Account Suspended – Layerfive Calibration System',
    html: `
      <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
        <div style="background:#0d1b3e;padding:20px;text-align:center">
          <h2 style="color:#fff">Layerfive Ltd</h2>
        </div>
        <div style="padding:30px;background:#fff;border:1px solid #e5e7eb">
          <h3>Account Suspended</h3>
          <p>Hello ${user.full_name}, your account has been suspended. Please contact your administrator.</p>
        </div>
      </div>
    `
  });
}

module.exports = {
  sendApprovalNotification,
  sendNewUserNotification,
  sendPasswordResetEmail,
  sendExpiryNotification,
  sendSuspensionEmail
};
