import { Resend } from "resend";

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

let cachedResend: Resend | null = null;
function getResend(): Resend {
  if (!env.RESEND_API_KEY) {
    throw new Error(
      "RESEND_API_KEY is not configured — cannot send transactional emails. Set it in your environment.",
    );
  }
  cachedResend ??= new Resend(env.RESEND_API_KEY);
  return cachedResend;
}

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 InvitationEmailArgs = {
  to: string;
  inviterName: string;
  organizationName: string;
  role: string;
  acceptUrl: string;
};

export async function sendInvitationEmail(args: InvitationEmailArgs) {
  const subject = `${args.inviterName} invited you to ${args.organizationName} on Eleva Speed`;
  const html = renderHtml(args);
  const text = renderText(args);

  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 renderHtml(args: InvitationEmailArgs): string {
  return `<!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;">You've been invited to ${escapeHtml(args.organizationName)}</h1>
    <p style="line-height: 1.5; color: #52525b;">
      <strong>${escapeHtml(args.inviterName)}</strong> invited you to join
      <strong>${escapeHtml(args.organizationName)}</strong> on Eleva Speed as
      <strong>${escapeHtml(args.role)}</strong>.
    </p>
    <p style="margin: 32px 0;">
      <a href="${args.acceptUrl}" style="display: inline-block; padding: 12px 20px; background: rgb(253, 16, 94); color: white; text-decoration: none; border-radius: 8px; font-weight: 600;">
        Accept invitation
      </a>
    </p>
    <p style="font-size: 12px; color: #71717a;">
      If you weren't expecting this invitation, you can safely ignore this email.
    </p>
  </body>
</html>`;
}

function renderText(args: InvitationEmailArgs): string {
  return `${args.inviterName} invited you to join ${args.organizationName} on Eleva Speed as ${args.role}.

Accept the invitation: ${args.acceptUrl}

If you weren't expecting this, you can safely ignore this email.`;
}

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