const nodemailer = require("nodemailer");

function envStr(key) {
  const v = process.env[key];
  return v ? String(v).trim().replace(/^["']|["']$/g, "") : "";
}

function isMailConfigured() {
  return Boolean(envStr("MAIL_HOST") && envStr("MAIL_PASSWORD") && (envStr("MAIL_USER") || envStr("MAIL_HOST_USER")));
}

function createTransporter() {
  const host = envStr("MAIL_HOST");
  const port = Number(envStr("MAIL_PORT")) || 465;
  const user = envStr("MAIL_USER") || envStr("MAIL_HOST_USER");
  const pass = envStr("MAIL_PASSWORD");

  return nodemailer.createTransport({
    host,
    port,
    secure: port === 465,
    auth: { user, pass },
  });
}

function frontendUrl() {
  return envStr("FRONTEND_URL") || "http://localhost:5173";
}

function fromAddress() {
  return envStr("MAIL_FROM") || `SMARTPOS <${envStr("MAIL_USER") || envStr("MAIL_HOST_USER")}>`;
}

function baseHtml({ title, body, ctaHref, ctaLabel }) {
  const company = envStr("VITE_COMPANY_NAME") || "SMARTPOS";
  return `<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>${title}</title></head>
<body style="font-family:system-ui,sans-serif;background:#f5f5f5;padding:24px;margin:0">
  <div style="max-width:520px;margin:0 auto;background:#fff;border-radius:8px;padding:32px;border:1px solid #e0e0e0">
    <h1 style="margin:0 0 8px;font-size:20px;color:#111">${company}</h1>
    <p style="margin:0 0 24px;color:#666;font-size:14px">${title}</p>
    <p style="color:#333;font-size:15px;line-height:1.5">${body}</p>
    ${
      ctaHref
        ? `<p style="margin:28px 0 0"><a href="${ctaHref}" style="display:inline-block;background:#599CE7;color:#fff;text-decoration:none;padding:12px 24px;border-radius:6px;font-weight:600">${ctaLabel}</a></p>`
        : ""
    }
    <p style="margin:24px 0 0;font-size:12px;color:#999">If you did not request this, you can ignore this email.</p>
  </div>
</body></html>`;
}

async function sendMail({ to, subject, html }) {
  if (!isMailConfigured()) {
    console.warn("[Mail] SMTP not configured — email not sent.");
    return false;
  }

  const transporter = createTransporter();
  await transporter.sendMail({
    from: fromAddress(),
    to,
    subject,
    html,
  });
  return true;
}

async function sendVerificationEmail(email, token) {
  const url = `${frontendUrl()}/verify-email?token=${encodeURIComponent(token)}`;
  const html = baseHtml({
    title: "Verify your email",
    body: "Please verify your email address to activate your SMARTPOS account.",
    ctaHref: url,
    ctaLabel: "Verify email",
  });

  if (!(await sendMail({ to: email, subject: "Verify your SMARTPOS account", html }))) {
    console.log(`[Mail] Verification link for ${email}: ${url}`);
  }
}

async function sendPasswordResetEmail(email, token) {
  const url = `${frontendUrl()}/reset-password?token=${encodeURIComponent(token)}`;
  const html = baseHtml({
    title: "Reset your password",
    body: "We received a request to reset your password. This link expires in 1 hour.",
    ctaHref: url,
    ctaLabel: "Reset password",
  });

  if (!(await sendMail({ to: email, subject: "Reset your SMARTPOS password", html }))) {
    console.log(`[Mail] Password reset link for ${email}: ${url}`);
  }
}

module.exports = {
  sendMail,
  sendVerificationEmail,
  sendPasswordResetEmail,
  isMailConfigured,
};
