import nodemailer from 'nodemailer';
import { env } from '../config/env.js';

// Build a transport only if SMTP is configured; otherwise we fall back to console.
let transporter = null;
if (env.smtp.host && env.smtp.user) {
  transporter = nodemailer.createTransport({
    host: env.smtp.host,
    port: env.smtp.port,
    secure: env.smtp.secure || env.smtp.port === 465,
    auth: { user: env.smtp.user, pass: env.smtp.pass },
  });
}

export const mailEnabled = Boolean(transporter);

async function send({ to, subject, html, text }) {
  if (!transporter) {
    console.log(`\n[mail:console] To: ${to}\n[mail:console] Subject: ${subject}\n[mail:console] ${text || html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()}\n`);
    return;
  }
  await transporter.sendMail({ from: env.smtp.from, to, subject, html, text });
}

const brand = '#2563eb';
function layout(title, bodyHtml) {
  return `
  <div style="font-family:-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;max-width:480px;margin:0 auto;padding:24px;color:#1f2937">
    <h2 style="color:${brand};margin:0 0 4px">CertsNexus</h2>
    <h3 style="margin:16px 0 8px">${title}</h3>
    ${bodyHtml}
    <p style="color:#9ca3af;font-size:12px;margin-top:24px">If you didn't request this, you can safely ignore this email.</p>
  </div>`;
}

function codeBlock(code) {
  return `<div style="font-size:30px;letter-spacing:8px;font-weight:700;background:#f3f4f6;border-radius:10px;padding:14px 0;text-align:center;margin:12px 0">${code}</div>`;
}

export function sendOtpEmail(to, code, purpose) {
  const isReset = purpose === 'PASSWORD_RESET';
  const subject = isReset ? 'Your CertsNexus password reset code' : 'Your CertsNexus verification code';
  const intro = isReset
    ? 'Use this code to reset your password:'
    : 'Use this code to verify your email address:';
  const html = layout(isReset ? 'Reset your password' : 'Verify your email', `
    <p>${intro}</p>
    ${codeBlock(code)}
    <p style="color:#6b7280;font-size:14px">This code expires in <b>1 minute</b>.</p>`);
  return send({ to, subject, html, text: `${intro} ${code} (expires in 1 minute)` });
}

export function sendWelcomeEmail(to, name) {
  const first = (name || '').split(' ')[0] || 'there';
  const html = layout('Welcome to CertsNexus 🎉', `
    <p>Hi ${first}, your email is verified and your account is ready.</p>
    <p>Jump in, pick a certification, and start practicing.</p>`);
  return send({ to, subject: 'Welcome to CertsNexus', html, text: `Hi ${first}, your CertsNexus account is ready.` });
}

export function sendPasswordChangedEmail(to) {
  const html = layout('Your password was changed', `
    <p>Your CertsNexus password was just updated. If this wasn't you, please reset it immediately or contact support.</p>`);
  return send({ to, subject: 'Your CertsNexus password was changed', html, text: 'Your CertsNexus password was just changed.' });
}
