import { createError, readBody } from "h3"
import { getMysqlPool } from "~~/server/utils/mysql"
import { sendParcDemandEmails } from "~~/server/utils/mailer"

function normalizeValue(value) {
  return typeof value === "string" ? value.trim() : ""
}

function isValidEmail(email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
}

export default defineEventHandler(async (event) => {
  const body = await readBody(event)

  const payload = {
    requestType: normalizeValue(body?.requestType),
    name: normalizeValue(body?.name),
    email: normalizeValue(body?.email),
    phone: normalizeValue(body?.phone),
    organization: normalizeValue(body?.organization),
    message: normalizeValue(body?.message),
  }

  if (!payload.requestType || !payload.name || !payload.email || !payload.phone || !payload.organization || !payload.message) {
    throw createError({
      statusCode: 400,
      statusMessage: "Tous les champs obligatoires doivent être remplis.",
    })
  }

  if (!isValidEmail(payload.email)) {
    throw createError({
      statusCode: 400,
      statusMessage: "L’adresse email n’est pas valide.",
    })
  }

  if (payload.message.length > 5000) {
    throw createError({
      statusCode: 400,
      statusMessage: "Le message est trop long.",
    })
  }

  const db = getMysqlPool()

  try {
    const [result] = await db.execute(
      `
        INSERT INTO parc_demandes (type_demande, nom, email, telephone, organisme, message)
        VALUES (?, ?, ?, ?, ?, ?)
      `,
      [payload.requestType, payload.name, payload.email, payload.phone, payload.organization, payload.message]
    )

    const emailsSent = await sendParcDemandEmails(payload)

    return {
      ok: true,
      id: result.insertId,
      emailsSent,
    }
  } catch (error) {
    console.error("Erreur API parc-demandes:", error)

    throw createError({
      statusCode: 500,
      statusMessage: "Impossible d’enregistrer la demande pour le moment.",
    })
  }
})
