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

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

  if (!body?.slug || !body?.title) {
    throw createError({ statusCode: 400, statusMessage: 'Missing slug or title' })
  }

  if (!/^[a-z0-9-]+$/.test(body.slug)) {
    throw createError({ statusCode: 400, statusMessage: 'Invalid slug format' })
  }

  const filePath = join(process.cwd(), 'content', 'book', `${body.slug}.md`)

  const content = `---
title: "${body.title}"
description: ""
order: ${body.order}
readingTime: "5 min"
---

`

  await writeFile(filePath, content, 'utf-8')
  gitSyncContent(`Nouveau chapitre ${body.slug}`, [`content/book/${body.slug}.md`])

  return { ok: true, slug: body.slug }
})
