export default defineEventHandler(async (event) => {
  const body = await readBody<{ author: string; email?: string; text: string }>(event)

  if (!body.author?.trim() || !body.text?.trim()) {
    throw createError({ statusCode: 400, statusMessage: 'Nom et message requis' })
  }

  const data = await readYaml<{ messages: any[] }>('messages.yml')

  const maxId = data.messages.reduce((max, m) => Math.max(max, m.id || 0), 0)

  data.messages.push({
    id: maxId + 1,
    author: body.author.trim(),
    email: body.email?.trim() || '',
    text: body.text.trim(),
    published: false,
    createdAt: new Date().toISOString(),
  })

  await writeYaml('messages.yml', data)

  return { ok: true }
})
