import nodemailer from "nodemailer";
import { getEffectiveSmtpSettings } from "@/lib/queries/system-settings-queries";

/** Create a nodemailer transport from DB/env SMTP settings. */
export async function createMailTransport() {
  const smtp = await getEffectiveSmtpSettings();
  if (!smtp.host) return null;

  return nodemailer.createTransport({
    host: smtp.host,
    port: smtp.port,
    secure: smtp.port === 465,
    auth:
      smtp.user && smtp.password
        ? { user: smtp.user, pass: smtp.password }
        : undefined,
  });
}

/** Send a single email via configured SMTP. */
export async function sendEmail(options: {
  to: string;
  subject: string;
  html: string;
}): Promise<{ ok: boolean; error?: string }> {
  const transport = await createMailTransport();
  if (!transport) {
    return { ok: false, error: "SMTP is not configured" };
  }

  const smtp = await getEffectiveSmtpSettings();

  try {
    await transport.sendMail({
      from: smtp.from,
      to: options.to,
      subject: options.subject,
      html: options.html,
    });
    return { ok: true };
  } catch (err) {
    const message = err instanceof Error ? err.message : "Send failed";
    return { ok: false, error: message };
  }
}
