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

export default defineEventHandler(async (event) => {
  try {
    const { menuId, reference } = await readBody<{
      menuId: string
      reference: string
    }>(event)
    
    if (!menuId || !reference) {
      throw createError({
        statusCode: 400,
        statusMessage: 'MenuId and reference are required'
      })
    }
    
    const filePath = path.join(process.cwd(), 'matdash', 'data', 'menus.json')
    const fileContent = await fs.readFile(filePath, 'utf-8')
    const data = JSON.parse(fileContent)
    
    // Remove menu item and its children recursively
    const removeMenuItem = (items: any[], id: string): any[] => {
      return items.filter(item => {
        if (item.id === id) return false
        if (item.children) {
          item.children = removeMenuItem(item.children, id)
        }
        return true
      })
    }
    
    data.menus = removeMenuItem(data.menus, menuId)
    
    // Save updated data
    await fs.writeFile(filePath, JSON.stringify(data, null, 2))
    
    return {
      success: true,
      message: 'Menu deleted successfully'
    }
  } catch (error) {
    console.error('Error deleting menu:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to delete menu'
    })
  }
})
