import fs from 'fs/promises'
import path from 'path'

export default defineEventHandler(async (event) => {
  try {
    const filePath = path.join(process.cwd(), 'matdash', 'data', 'menus.json')
    
    // Check if file exists, create if not
    try {
      await fs.access(filePath)
    } catch {
      const defaultData = {
        menus: [],
        references: ["Referensi", "Main", "Admin"],
        menuOptions: ["Select a menu", "Main Menu", "Side Menu", "Footer Menu"]
      }
      await fs.writeFile(filePath, JSON.stringify(defaultData, null, 2))
    }
    
    const fileContent = await fs.readFile(filePath, 'utf-8')
    const data = JSON.parse(fileContent)
    
    return {
      success: true,
      data
    }
  } catch (error) {
    console.error('Error reading menus:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to load menus'
    })
  }
})
