import { getEnv } from "@/core/config/env";

export type MailMessage = {
  to: string;
  subject: string;
  text: string;
  html?: string;
};

/**
 * Lightweight transactional mailer.
 * - console: logs to stdout (local/dev)
 * - resend: HTTPS API when EMAIL_API_KEY is set
 * - smtp: reserved; falls back to console until SMTP transport is wired
 */
export async function sendMail(message: MailMessage): Promise<void> {
  const env = getEnv();
  const from = env.EMAIL_FROM;

  if (env.EMAIL_PROVIDER === "resend") {
    if (!env.EMAIL_API_KEY) {
      throw new Error("EMAIL_API_KEY is required for Resend");
    }

    const response = await fetch("https://api.resend.com/emails", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${env.EMAIL_API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        from,
        to: [message.to],
        subject: message.subject,
        text: message.text,
        html: message.html ?? message.text.replace(/\n/g, "<br />"),
      }),
    });

    if (!response.ok) {
      const detail = await response.text().catch(() => "");
      throw new Error(
        `Resend failed (${response.status})${detail ? `: ${detail}` : ""}`,
      );
    }
    return;
  }

  // console + smtp fallback for local/dev until SMTP is configured
  console.info("[mail]", {
    provider: env.EMAIL_PROVIDER,
    from,
    to: message.to,
    subject: message.subject,
    text: message.text,
  });
}
