import { sendEmail } from "@/lib/services/email-sender";

const FROM_NAME = "meSEO";
const AUDIT_URL = process.env.NEXT_PUBLIC_AUDIT_URL ?? "https://audit.meseoapp.com";

function buildHtml(code: string): string {
  return `<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background:#f1f5f9;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0">
<tr><td align="center" style="padding:40px 16px">
<table role="presentation" width="480" cellpadding="0" cellspacing="0"
  style="background:#fff;border-radius:16px;overflow:hidden;max-width:480px;width:100%;box-shadow:0 1px 3px rgba(0,0,0,0.08)">

  <tr><td style="background:#0f172a;padding:28px 32px;text-align:center">
    <p style="margin:0;font-size:20px;font-weight:800;color:#fff;letter-spacing:-0.5px">meSEO</p>
    <p style="margin:6px 0 0;font-size:12px;color:#94a3b8;letter-spacing:1px;text-transform:uppercase">AI Search Audit</p>
  </td></tr>

  <tr><td style="padding:40px 32px;text-align:center">
    <p style="margin:0 0 6px;font-size:15px;font-weight:600;color:#0f172a">Your verification code</p>
    <p style="margin:0 0 28px;font-size:14px;color:#64748b;line-height:1.5">
      Enter this code in your browser to start your free AI search audit.
    </p>

    <div style="background:#f8fafc;border:2px solid #e2e8f0;border-radius:12px;padding:24px 32px;margin:0 auto 28px;display:inline-block">
      <p style="margin:0;font-size:42px;font-weight:800;letter-spacing:10px;color:#0f172a;font-family:'Courier New',Courier,monospace">
        ${code}
      </p>
    </div>

    <p style="margin:0 0 8px;font-size:13px;color:#94a3b8">
      This code expires in <strong style="color:#475569">10 minutes</strong>.
    </p>
    <p style="margin:0;font-size:13px;color:#94a3b8">
      If you didn&rsquo;t request this audit, you can safely ignore this email.
    </p>
  </td></tr>

  <tr><td style="padding:16px 32px;border-top:1px solid #f1f5f9;background:#f8fafc;text-align:center">
    <p style="margin:0;font-size:11px;color:#94a3b8">
      Sent by meSEO &mdash; <a href="${AUDIT_URL}" style="color:#6366f1;text-decoration:none">meseoapp.com</a>
    </p>
  </td></tr>

</table>
</td></tr>
</table>
</body>
</html>`;
}

export async function sendVerificationCode(email: string, code: string): Promise<boolean> {
  const result = await sendEmail(
    [email],
    "Your meSEO audit verification code",
    buildHtml(code),
    { fromName: FROM_NAME },
  );
  console.log(`[verification-email] sent to=${email} result=${result.success ? "ok" : result.error}`);
  return result.success;
}
