/**
 * Transactional email delivery via Resend API.
 */

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

interface SendEmailParams {
  to: string;
  subject: string;
  html: string;
  from?: string;
}

export async function sendEmail(
  params: SendEmailParams,
  resendApiKey: string
): Promise<void> {
  // Validate email format
  if (!EMAIL_RE.test(params.to)) {
    throw new Error("Invalid recipient email address");
  }

  // Sanitize subject — strip newlines to prevent header injection
  const sanitizedSubject = params.subject.replace(/[\r\n\0]/g, "");

  const response = await fetch("https://api.resend.com/emails", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${resendApiKey}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      from: params.from ?? "StyloBridge <noreply@stylobridge.ai>",
      to: [params.to],
      subject: sanitizedSubject,
      html: params.html,
    }),
  });

  if (!response.ok) {
    const body = await response.text();
    throw new Error(`Resend API error (${response.status}): ${body}`);
  }
}
