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",
    connectionTimeout: 10000,
    greetingTimeout: 10000,
    socketTimeout: 15000,
    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
}

function formatProjetLyceePriority(priority) {
  if (priority === null || priority === undefined) return "Non renseigné"
  if (priority === 0) return "Non souhaité"
  return `Priorité ${priority}`
}

function getProjetLyceeSummary(payload) {
  const projectWishes = [
    ["Concert-rencontre", payload.concertRencontrePriority],
    ["Parcours Entrer dans la peau d'un professionnel du spectacle", payload.immersionPriority],
    ["Parcours EAC", payload.eacPriority],
    ["Concert commente", payload.concertCommentePriority],
  ]
    .filter(([, priority]) => priority >= 1 && priority <= 4)
    .map(([label, priority]) => `${label} : ${formatProjetLyceePriority(priority)}`)

  return [
    `Etablissement scolaire : ${payload.schoolName}`,
    `Departement : ${payload.department}`,
    `Ville : ${payload.city}`,
    `Enseignant coordinateur : ${payload.coordinatorName}`,
    `Email : ${payload.email}`,
    `Telephone : ${payload.phone}`,
    `Discipline enseignee : ${payload.discipline}`,
    `Niveau de classe : ${payload.classLevel}`,
    `Nombre probable d'eleves concernes : ${payload.studentCount}`,
    ...(projectWishes.length ? ["", "Souhaits de projet :", ...projectWishes] : []),
    "",
    "Periode souhaitée :",
    payload.projectPeriod,
  ].join("\n")
}

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

  if (!mailer) {
    console.warn("Email projet lycée non envoyé: configuration SMTP incomplète.")
    return false
  }

  if (!config.scolaireRequestRecipientEmail) {
    console.warn("Email projet lycée non envoyé: destinataire scolaire manquant.")
    return false
  }

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

  const summary = getProjetLyceeSummary(payload)

  const adminSubject = `WONDIF - Candidature projet lycee - ${payload.schoolName}`
  const adminText = [
    "Une nouvelle candidature a été envoyée depuis le formulaire Projet lycée.",
    "",
    summary,
  ].join("\n")

  const userSubject = "ONDIF - Confirmation de votre candidature - Projet lycée"
  const userText = [
    `Bonjour ${payload.coordinatorName},`,
    "",
    "Votre candidature à un projet avec l'Orchestre national d'Île-de-France a bien été transmise.",
    "L'équipe d'action culturelle reviendra vers vous d'ici fin juin 2026 afin de vous informer de la suite donnée à votre candidature.",
    "",
    "Recapitulatif :",
    summary,
  ].join("\n")

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

  return true
}
