import nodemailer from 'nodemailer' const SETTINGS_URL = process.env.SETTINGS_URL || 'http://10.10.10.106:3080' const SETTINGS_SECRET = process.env.SETTINGS_SECRET || '' let _smtpCache = null // { config, expires_at } let _transporter = null async function getSmtpConfig() { if (_smtpCache && Date.now() < _smtpCache.expires_at) return _smtpCache.config const res = await fetch(`${SETTINGS_URL}/settings/api/internal/integration/smtp`, { headers: { Authorization: `Bearer ${SETTINGS_SECRET}` }, signal: AbortSignal.timeout(5000), }) if (!res.ok) throw new Error(`Failed to fetch SMTP config from settings: ${res.status}`) const config = await res.json() if (!config.host) throw new Error('SMTP not configured in settings') _smtpCache = { config, expires_at: Date.now() + 5 * 60_000 } _transporter = null // force transporter rebuild on next send return config } async function getTransporter() { if (_transporter) return _transporter const config = await getSmtpConfig() const port = parseInt(config.port || '587') _transporter = nodemailer.createTransport({ host: config.host, port, secure: port === 465, auth: config.user ? { user: config.user, pass: config.pass } : undefined, }) return _transporter } export async function sendPinEmail(to, name, pin) { const config = await getSmtpConfig() const transport = await getTransporter() const from = config.from || '"Hotel Number Four" ' await transport.sendMail({ from, to, subject: 'Your Hotel Number Four verification code', text: `Hi ${name},\n\nYour staff portal verification code is: ${pin}\n\nThis code expires in 15 minutes.\n\nIf you did not request this, please ignore this email.`, html: `

Hotel Number Four

Hi ${name},

Your staff portal verification code is:

${pin}

This code expires in 15 minutes.
If you did not request access to the staff portal, please ignore this email.

`, }) }