import nodemailer from "nodemailer";

type EmailAttachment = {
  filename: string;
  content: string;
};

type WebsiteEmail = {
  to: string;
  subject: string;
  html: string;
  replyTo?: string;
  attachments?: EmailAttachment[];
};

export async function sendWebsiteEmail(message: WebsiteEmail) {
  const host = process.env["SMTP_HOST"];
  const user = process.env["SMTP_USER"];
  const password = process.env["SMTP_PASSWORD"];
  const from = process.env["SMTP_FROM_EMAIL"] || user;
  const port = Number(process.env["SMTP_PORT"] || 465);

  if (!host || !user || !password || !from || !Number.isInteger(port)) {
    console.error("[email] cPanel SMTP environment variables are incomplete.");
    throw new Error("The email service is not configured.");
  }

  const transporter = nodemailer.createTransport({
    host,
    port,
    secure: port === 465,
    auth: { user, pass: password },
  });

  await transporter.sendMail({
    from,
    to: message.to,
    subject: message.subject,
    html: message.html,
    replyTo: message.replyTo,
    attachments: message.attachments?.map((attachment) => ({
      filename: attachment.filename,
      content: attachment.content,
      encoding: "base64",
    })),
  });
}
