import { Resend } from "resend";

let client: Resend | null = null;

function getClient(): Resend {
  const apiKey = process.env.EMAIL_PROVIDER_API_KEY;
  if (!apiKey) {
    throw new Error(
      "EMAIL_PROVIDER_API_KEY is not set — add a Resend API key to .env.local before submissions can send email."
    );
  }
  client ??= new Resend(apiKey);
  return client;
}

export interface SendEmailInput {
  to: string;
  subject: string;
  html: string;
  replyTo?: string;
}

/** Thin wrapper around Resend so API routes don't touch the SDK directly and every send goes through one FROM_EMAIL. */
export async function sendEmail({ to, subject, html, replyTo }: SendEmailInput): Promise<void> {
  const from = process.env.FROM_EMAIL;
  if (!from) {
    throw new Error("FROM_EMAIL is not set — add a verified sending address to .env.local.");
  }

  const { error } = await getClient().emails.send({
    from,
    to,
    subject,
    html,
    ...(replyTo ? { replyTo } : {}),
  });

  if (error) {
    throw new Error(`Resend failed to send "${subject}" to ${to}: ${error.message}`);
  }
}
