import { mkdir } from 'node:fs/promises'
import { join, dirname } from 'node:path'

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

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

  const body = await readBody(event)
  const relativePath = `pages/${path}.yml`

  // Ensure subdirectory exists
  const fullPath = join(process.cwd(), 'site', relativePath)
  await mkdir(dirname(fullPath), { recursive: true })

  await writeYaml(relativePath, body)
  gitSyncContent(`Mise à jour page ${path}`, [`site/${relativePath}`])
  return { ok: true }
})
