import nodemailer, { type Transporter } from "nodemailer"

// SMTP transport (SMTP2GO). Created lazily so importing this on the auth path
// doesn't require SMTP to be configured. Sends fail gracefully in sendEmail().
const SMTP_HOST = process.env.SMTP_HOST
const SMTP_PORT = Number(process.env.SMTP_PORT ?? 587)
const SMTP_USER = process.env.SMTP_USER
const SMTP_PASS = process.env.SMTP_PASS

export const FROM_EMAIL =
  process.env.EMAIL_FROM ??
  process.env.SMTP_FROM ??
  "postmaster@propertymanagement.network"
export const APP_NAME = process.env.NEXT_PUBLIC_APP_NAME ?? "Property Management Network"

/** True when SMTP is configured (host + credentials present). */
export function emailConfigured(): boolean {
  return Boolean(SMTP_HOST && SMTP_USER && SMTP_PASS)
}

let _transporter: Transporter | null = null
export function getTransporter(): Transporter {
  if (!_transporter) {
    _transporter = nodemailer.createTransport({
      host: SMTP_HOST,
      port: SMTP_PORT,
      // Port 465 uses implicit TLS/SSL; 587/2525/etc. negotiate STARTTLS.
      secure: SMTP_PORT === 465,
      auth: SMTP_USER && SMTP_PASS ? { user: SMTP_USER, pass: SMTP_PASS } : undefined,
    })
  }
  return _transporter
}
