export default defineEventHandler(async (event) => {
  const id = Number(getRouterParam(event, 'id'))

  if (!id || isNaN(id)) {
    throw createError({ statusCode: 400, statusMessage: 'ID invalide' })
  }

  const body = await readBody<{ text?: string; published?: boolean; author?: string }>(event)
  const data = await readYaml<{ messages: any[] }>('messages.yml')

  const message = data.messages.find(m => m.id === id)
  if (!message) {
    throw createError({ statusCode: 404, statusMessage: 'Message non trouvé' })
  }

  if (body.text !== undefined) message.text = body.text
  if (body.published !== undefined) message.published = body.published
  if (body.author !== undefined) message.author = body.author

  await writeYaml('messages.yml', data)

  return { ok: true }
})
