import nodemailer, { type Transporter } from "nodemailer";
import { env } from "./env";

let transporterPromise: Promise<Transporter> | null = null;

async function getTransporter(): Promise<Transporter> {
  if (transporterPromise) return transporterPromise;

  transporterPromise = (async () => {
    if (env.SMTP_HOST && env.SMTP_USER && env.SMTP_PASS) {
      const port = env.SMTP_PORT ?? 587;
      return nodemailer.createTransport({
        host: env.SMTP_HOST,
        port,
        // Port 465 is implicit TLS (negotiated from the first byte); 587/25 use
        // STARTTLS, upgrading an initially plaintext connection. Getting this
        // wrong for 465 fails/hangs instead of erroring clearly.
        secure: port === 465,
        auth: { user: env.SMTP_USER, pass: env.SMTP_PASS },
      });
    }

    const testAccount = await nodemailer.createTestAccount();
    console.log(
      `[mailer] No SMTP configured — using Ethereal test inbox (${testAccount.user})`
    );
    return nodemailer.createTransport({
      host: "smtp.ethereal.email",
      port: 587,
      auth: { user: testAccount.user, pass: testAccount.pass },
    });
  })();

  return transporterPromise;
}

export async function sendEmail(options: {
  to: string;
  subject: string;
  html: string;
}): Promise<void> {
  const transporter = await getTransporter();
  console.log(`[mailer] Sending "${options.subject}" to ${options.to} via ${env.SMTP_HOST ?? "Ethereal"}...`);

  const info = await transporter.sendMail({
    from: env.EMAIL_FROM,
    to: options.to,
    subject: options.subject,
    html: options.html,
  });

  // Always log the SMTP server's own response — "accepted" here means the
  // sending mail server took responsibility for it, not that it landed in the
  // inbox (spam filtering, SPF/DKIM, greylisting etc. happen after this point).
  console.log(
    `[mailer] Accepted by SMTP server. messageId=${info.messageId} response="${info.response}" accepted=${JSON.stringify(info.accepted)} rejected=${JSON.stringify(info.rejected)}`
  );

  const previewUrl = nodemailer.getTestMessageUrl(info);
  if (previewUrl) {
    console.log(`[mailer] Preview: ${previewUrl}`);
  }
}

export function emailTemplate(options: { title: string; bodyHtml: string; ctaLabel?: string; ctaUrl?: string }): string {
  return `
  <div style="font-family: -apple-system, Segoe UI, Roboto, sans-serif; max-width: 480px; margin: 0 auto; padding: 32px 24px;">
    <div style="font-size: 20px; font-weight: 700; color: #4f46e5; margin-bottom: 24px;">My Assisto</div>
    <h1 style="font-size: 18px; color: #17171c; margin: 0 0 12px;">${options.title}</h1>
    <div style="font-size: 14px; color: #4b4b55; line-height: 1.6;">${options.bodyHtml}</div>
    ${
      options.ctaUrl
        ? `<a href="${options.ctaUrl}" style="display:inline-block; margin-top: 20px; padding: 10px 18px; background:#4f46e5; color:#fff; border-radius: 8px; text-decoration:none; font-size: 14px;">${options.ctaLabel ?? "View"}</a>`
        : ""
    }
  </div>`;
}
