const EMPTY = { messages: [] as any[] }

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

  if (!body.text?.trim()) {
    throw createError({ statusCode: 400, statusMessage: 'Message requis' })
  }

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

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

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

  await writeDataYaml('messages.yml', data)

  return { ok: true }
})
