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

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
    type?: string
    reply?: string | null
  }>(event)

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

  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
  if (body.type !== undefined) message.type = body.type
  if ('reply' in body) {
    message.reply = body.reply
      ? { text: body.reply, publishedAt: new Date().toISOString() }
      : null
  }

  await writeDataYaml('messages.yml', data)

  return { ok: true }
})
