import type { Payload } from 'payload'

/**
 * The site's outgoing mail: the same Office 365 mailbox the learning platform sends from, so a message
 * about a new request looks like it came from the academy rather than from a web form.
 *
 * With no SMTP_HOST set, Payload keeps its own console transport: nothing leaves the machine, and a
 * developer sees the message in the logs instead. That is what a local copy should do.
 */
export function smtpFromEnv() {
  const host = (process.env.SMTP_HOST || '').trim()
  if (!host) return null
  const port = Number(process.env.SMTP_PORT || 587)
  return {
    defaultFromAddress: (process.env.SMTP_FROM || process.env.SMTP_USER || '').trim(),
    defaultFromName: (process.env.SMTP_FROM_NAME || 'Thinkera').trim(),
    transportOptions: {
      host,
      port,
      // 587 upgrades through STARTTLS, 465 is TLS from the first byte
      secure: port === 465,
      requireTLS: port !== 465,
      auth: { user: (process.env.SMTP_USER || '').trim(), pass: process.env.SMTP_PASS || '' },
    },
  }
}

/**
 * Where the academy's own notices go. The CMS setting wins, so the address can be changed at
 * /admin without a deploy; NOTIFY_EMAIL in .env is the fallback the server starts with.
 */
export async function notifyAddress(payload: Payload): Promise<string> {
  const fallback = (process.env.NOTIFY_EMAIL || '').trim()
  try {
    const settings = (await payload.findGlobal({ slug: 'settings', depth: 0 })) as { notifyEmail?: string | null }
    const chosen = (settings?.notifyEmail || '').trim()
    return chosen || fallback
  } catch {
    return fallback
  }
}
