import { Resend } from "resend";

import { env } from "@/lib/env";

let cached: Resend | null = null;

function getResend(): Resend {
  if (cached) return cached;
  if (!env.RESEND_API_KEY) {
    throw new Error("RESEND_API_KEY is not configured");
  }
  cached = new Resend(env.RESEND_API_KEY);
  return cached;
}

function getFrom(): string {
  if (!env.RESEND_FROM_EMAIL) {
    throw new Error(
      "RESEND_FROM_EMAIL is not configured. Set it in .env.local to a sender on a domain you verified at resend.com/domains (e.g. `Eleva Speed <hello@elevaseo.com>`). The Resend sandbox sender `onboarding@resend.dev` only delivers to the account owner's email and is not a usable fallback.",
    );
  }
  return env.RESEND_FROM_EMAIL;
}

export type OTPEmailType = "sign-in" | "email-verification" | "forget-password" | "change-email";

export type OTPEmailArgs = {
  to: string;
  otp: string;
  type: OTPEmailType;
};

function subjectFor(type: OTPEmailType): string {
  switch (type) {
    case "email-verification":
      return "Verify your Eleva Speed email";
    case "forget-password":
      return "Reset your Eleva Speed password";
    case "change-email":
      return "Confirm your new email on Eleva Speed";
    case "sign-in":
      return "Your Eleva Speed sign-in code";
  }
}

function bodyTextFor(type: OTPEmailType): string {
  switch (type) {
    case "email-verification":
      return "Use this code to verify your email address.";
    case "forget-password":
      return "Use this code to reset your password.";
    case "change-email":
      return "Use this code to confirm your new email address.";
    case "sign-in":
      return "Use this code to sign in.";
  }
}

export async function sendOTPEmail(args: OTPEmailArgs): Promise<string | null> {
  const subject = subjectFor(args.type);
  const intro = bodyTextFor(args.type);

  const html = `<!doctype html>
<html lang="en">
  <body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 480px; margin: 40px auto; color: #18181b;">
    <h1 style="font-size: 22px; margin-bottom: 16px;">${escapeHtml(subject)}</h1>
    <p style="line-height: 1.5; color: #52525b;">${escapeHtml(intro)}</p>
    <div style="margin: 32px 0; text-align: center;">
      <div style="display: inline-block; padding: 20px 32px; background: #fafafa; border: 1px solid #e4e4e7; border-radius: 12px; font-family: 'SF Mono', Monaco, Menlo, monospace; font-size: 32px; font-weight: 700; letter-spacing: 6px; color: rgb(253, 16, 94);">
        ${escapeHtml(args.otp)}
      </div>
    </div>
    <p style="font-size: 12px; color: #71717a;">
      This code expires in 5 minutes. If you didn't request it, ignore this email.
    </p>
  </body>
</html>`;

  const text = `${subject}

${intro}

Code: ${args.otp}

This code expires in 5 minutes. If you didn't request it, ignore this email.`;

  const result = await getResend().emails.send({
    from: getFrom(),
    to: args.to,
    subject,
    html,
    text,
  });

  if (result.error) {
    throw new Error(`Resend failed: ${result.error.message}`);
  }
  return result.data?.id ?? null;
}

function escapeHtml(s: string): string {
  return s
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}
