import { readdir, stat } from 'node:fs/promises'
import { join } from 'node:path'

interface PageEntry {
  path: string
  label: string
  section?: string
}

async function listYamlFiles(dir: string, prefix = ''): Promise<PageEntry[]> {
  const entries: PageEntry[] = []
  const items = await readdir(dir)

  for (const item of items) {
    const fullPath = join(dir, item)
    const s = await stat(fullPath)

    if (s.isDirectory()) {
      const subEntries = await listYamlFiles(fullPath, prefix ? `${prefix}/${item}` : item)
      entries.push(...subEntries)
    }
    else if (item.endsWith('.yml')) {
      const name = item.replace('.yml', '')
      const path = prefix ? `${prefix}/${name}` : name
      entries.push({
        path,
        label: name,
        section: prefix || undefined,
      })
    }
  }

  return entries
}

export default defineEventHandler(async () => {
  const pagesDir = join(process.cwd(), 'site', 'pages')
  return await listYamlFiles(pagesDir)
})
