import nodemailer from 'nodemailer'

function hasSmtpEnv() {
  return Boolean(process.env.SMTP_HOST && process.env.SMTP_PORT && process.env.SMTP_USER && process.env.SMTP_PASS)
}

function createTransporter() {
  return nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number(process.env.SMTP_PORT),
    secure: process.env.SMTP_SECURE === 'true',
    connectionTimeout: 5000,
    greetingTimeout: 5000,
    socketTimeout: 5000,
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS,
    },
  })
}

export async function sendLoginCodeEmail({ to, code }) {
  if (!hasSmtpEnv()) {
    console.info(`[DEV] login code for ${to}: ${code}`)
    return
  }

  try {
    const transporter = createTransporter()
    const from = process.env.MAIL_FROM || process.env.SMTP_USER

    await transporter.sendMail({
      from,
      to,
      subject: 'Код входа',
      text: `Ваш код: ${code}\n\nЕсли это были не вы — просто проигнорируйте письмо.`,
    })
  } catch (err) {
    console.error(`[email] Failed to send login code to ${to}: ${err.message}`)
    console.info(`[DEV] login code for ${to}: ${code}`)
  }
}

export async function sendNotificationEmail({ to, subject, html }) {
  if (!hasSmtpEnv()) {
    console.info(`[DEV] notification email to ${to}: ${subject}`)
    return { success: true }
  }

  try {
    const transporter = createTransporter()
    const from = process.env.MAIL_FROM || process.env.SMTP_USER

    await transporter.sendMail({
      from,
      to,
      subject,
      html,
    })
    return { success: true }
  } catch (err) {
    return { success: false, error: err.message }
  }
}
