import nodemailer from "nodemailer"

let transporter

function isSmtpConfigured(config) {
  return Boolean(
    config.smtpHost &&
    config.smtpPort &&
    config.smtpUser &&
    config.smtpPassword &&
    config.smtpFromEmail
  )
}

function getTransporter() {
  if (transporter) {
    return transporter
  }

  const config = useRuntimeConfig()

  if (!isSmtpConfigured(config)) {
    return null
  }

  transporter = nodemailer.createTransport({
    host: config.smtpHost,
    port: Number(config.smtpPort),
    secure: String(config.smtpSecure).toLowerCase() === "true",
    auth: {
      user: config.smtpUser,
      pass: config.smtpPassword,
    },
  })

  return transporter
}

export async function sendParcDemandEmails(payload) {
  const config = useRuntimeConfig()
  const mailer = getTransporter()

  if (!mailer || !config.parcRequestRecipientEmail) {
    return false
  }

  const from = config.smtpFromName
    ? `"${config.smtpFromName}" <${config.smtpFromEmail}>`
    : config.smtpFromEmail

  const adminSubject = `WONDIF - Formulaire de demande Parc instrumental - ${payload.name}`
  const adminText = [
    "Une nouvelle demande a été envoyée depuis le formulaire du Parc instrumental.",
    "",
    `Type de demande : ${payload.requestType}`,
    `Nom : ${payload.name}`,
    `Email : ${payload.email}`,
    `Telephone : ${payload.phone}`,
    `Structure : ${payload.organization}`,
    "",
    "Message :",
    payload.message,
  ].join("\n")

  const userSubject = "ONDIF - Confirmation de votre demande - Parc instrumental"
  const userText = [
    `Bonjour ${payload.name},`,
    "",
    "Votre demande a bien été transmise à l'équipe du Parc instrumental.",
    "Nous reviendrons vers vous dans les meilleurs délais.",
    "",
    "Recapitulatif :",
    `Type de demande : ${payload.requestType}`,
    `Structure : ${payload.organization}`,
    `Telephone : ${payload.phone}`,
    "",
    "Votre message :",
    payload.message,
  ].join("\n")

  await Promise.all([
    mailer.sendMail({
      from,
      to: config.parcRequestRecipientEmail,
      replyTo: payload.email,
      subject: adminSubject,
      text: adminText,
    }),
    mailer.sendMail({
      from,
      to: payload.email,
      subject: userSubject,
      text: userText,
    }),
  ])

  return true
}
