import nodemailer from 'nodemailer';

// SMTP notification layer. Safe no-op when SMTP_HOST is not configured —
// the DB write is always the source of truth, this is only the notify step.

const env = process.env;

function isConfigured() {
  return Boolean(env.SMTP_HOST && env.SMTP_FROM && env.ADMIN_EMAIL);
}

let transport: nodemailer.Transporter | null = null;
function getTransport() {
  if (!transport) {
    const port = Number(env.SMTP_PORT ?? 587);
    transport = nodemailer.createTransport({
      host: env.SMTP_HOST!,
      port,
      secure: port === 465,
      auth:
        env.SMTP_USER && env.SMTP_PASS
          ? { user: env.SMTP_USER, pass: env.SMTP_PASS }
          : undefined
    });
  }
  return transport;
}

export async function sendMail({
  to,
  subject,
  text,
  html
}: {
  to: string;
  subject: string;
  text: string;
  html?: string;
}) {
  if (!isConfigured()) {
    console.warn('[mailer] SMTP not configured — email skipped');
    return false;
  }
  try {
    await getTransport().sendMail({
      from: env.SMTP_FROM,
      to,
      subject,
      text,
      html
    });
    return true;
  } catch (err) {
    console.error('[mailer] send failed:', err);
    return false;
  }
}

export async function sendAdminNotification({
  subject,
  text
}: {
  subject: string;
  text: string;
}) {
  if (!env.ADMIN_EMAIL) return false;
  return sendMail({ to: env.ADMIN_EMAIL, subject, text });
}