import nodemailer from "nodemailer";
import { env } from "../env";

let transporterInstance: nodemailer.Transporter | null = null;

function getTransporter() {
  if (transporterInstance) return transporterInstance;

  if (!env.MAIL_HOST) {
    // In development, we might not have mail configured, so we log instead of throwing
    if (process.env.NODE_ENV === "development") {
      console.warn(
        "MAIL_HOST is not configured. Emails will be logged to console.",
      );
      return null;
    }
    throw new Error(
      "MAIL_HOST is not configured. Please check your environment variables.",
    );
  }

  transporterInstance = nodemailer.createTransport({
    host: env.MAIL_HOST,
    port: env.MAIL_PORT,
    secure: env.MAIL_PORT === 465,
    auth: {
      user: env.MAIL_USER,
      pass: env.MAIL_PASS,
    },
  });

  return transporterInstance;
}

interface SendEmailOptions {
  to?: string | string[];
  replyTo?: string;
  subject: string;
  html: string;
}

export async function sendEmail({
  to,
  replyTo,
  subject,
  html,
}: SendEmailOptions) {
  const recipients = to || env.MAIL_RECIPIENTS;
  const transporter = getTransporter();

  const mailOptions = {
    from: env.MAIL_FROM,
    to: recipients,
    replyTo,
    subject,
    html,
  };

  if (!transporter) {
    console.log("--- EMAIL SIMULATION ---");
    console.log("To:", recipients);
    console.log("Subject:", subject);
    console.log("HTML Output suppressed");
    console.log("--- END SIMULATION ---");
    return { success: true, messageId: "simulated-id" };
  }

  try {
    const info = await transporter.sendMail(mailOptions);
    console.log("Email sent successfully", {
      messageId: info.messageId,
      subject,
      recipients,
    });
    return { success: true, messageId: info.messageId };
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : String(error);
    console.error("Error sending email", {
      error: errorMsg,
      subject,
      recipients,
    });
    return { success: false, error: errorMsg };
  }
}
