import { readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'

export default defineEventHandler(async (event) => {
  const body = await readBody<{ chapters: { slug: string; order: number }[] }>(event)

  if (!body?.chapters || !Array.isArray(body.chapters)) {
    throw createError({ statusCode: 400, statusMessage: 'Missing chapters array' })
  }

  const bookDir = join(process.cwd(), 'content', 'book')

  await Promise.all(
    body.chapters.map(async ({ slug, order }) => {
      const filePath = join(bookDir, `${slug}.md`)
      const raw = await readFile(filePath, 'utf-8')

      // Replace order in frontmatter
      const updated = raw.replace(
        /^(---\n[\s\S]*?)order:\s*\d+/,
        `$1order: ${order}`,
      )

      await writeFile(filePath, updated, 'utf-8')
    }),
  )

  gitSyncContent('Réorganisation chapitres', ['content/book/'])

  return { ok: true }
})
