import nodemailer from "nodemailer";

// 复用 transporter 实例，避免每次发信都重新创建连接
let transporter: nodemailer.Transporter | null = null;

function getTransporter() {
  if (transporter) return transporter;

  transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number(process.env.SMTP_PORT ?? 465),
    secure: (Number(process.env.SMTP_PORT ?? 465) === 465),
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS,
    },
  });

  return transporter;
}

export async function sendMagicLinkEmail(email: string, url: string) {
  const fromName = process.env.SMTP_FROM_NAME ?? "鼎兴";
  const fromAddress = process.env.SMTP_FROM_ADDRESS ?? "no-reply@dingxing.com";

  const transport = getTransporter();

  await transport.sendMail({
    from: `"${fromName}" <${fromAddress}>`,
    to: email,
    subject: "【鼎兴】登录链接",
    html: magicLinkTemplate(url),
  });
}

function magicLinkTemplate(url: string): string {
  return `
<!DOCTYPE html>
<html lang="zh-CN">
<body style="margin:0;padding:0;background:#f4f4f5;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="padding:40px 0;">
    <tr>
      <td align="center">
        <table width="480" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,0.08);">
          <tr>
            <td style="background:#18181b;padding:24px 40px;text-align:center;">
              <span style="font-size:20px;font-weight:bold;color:#fafafa;">鼎兴</span>
            </td>
          </tr>
          <tr>
            <td style="padding:40px;">
              <h1 style="margin:0 0 16px;font-size:22px;color:#18181b;">登录到鼎兴管理后台</h1>
              <p style="margin:0 0 24px;font-size:15px;line-height:1.6;color:#52525b;">
                你收到这封邮件是因为有人请求使用此邮箱登录鼎兴。点击下方按钮即可完成登录：
              </p>
              <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td align="center">
                    <a href="${url}"
                       style="display:inline-block;padding:12px 32px;background:#18181b;color:#fafafa;text-decoration:none;font-size:15px;font-weight:600;border-radius:8px;">
                      登录
                    </a>
                  </td>
                </tr>
              </table>
              <p style="margin:24px 0 0;font-size:13px;color:#a1a1aa;">
                此链接将在 5 分钟后失效。如果你没有发起此请求，请忽略此邮件。
              </p>
              <hr style="margin:24px 0;border:none;border-top:1px solid #e4e4e7;">
              <p style="margin:0;font-size:12px;color:#a1a1aa;word-break:break-all;">
                或者复制此链接到浏览器：<br>${url}
              </p>
            </td>
          </tr>
        </table>
        <p style="margin:16px 0 0;font-size:12px;color:#a1a1aa;">
          © ${new Date().getFullYear()} 鼎兴. 保留所有权利.
        </p>
      </td>
    </tr>
  </table>
</body>
</html>
  `.trim();
}
