import fs from 'fs/promises'
import path from 'path'
import type { MenuItem } from '../../../types/menu'

export default defineEventHandler(async (event) => {
  try {
    const { menuItem, reference } = await readBody<{
      menuItem: MenuItem
      reference: string
    }>(event)
    
    if (!menuItem || !reference) {
      throw createError({
        statusCode: 400,
        statusMessage: 'MenuItem and reference are required'
      })
    }
    
    const filePath = path.join(process.cwd(), 'matdash', 'data', 'menus.json')
    
    // Read current data
    let data
    try {
      const fileContent = await fs.readFile(filePath, 'utf-8')
      data = JSON.parse(fileContent)
    } catch {
      data = { menus: [], references: [], menuOptions: [] }
    }
    
    // Update or add menu item
    const existingIndex = data.menus.findIndex((item: MenuItem) => item.id === menuItem.id)
    
    if (existingIndex >= 0) {
      data.menus[existingIndex] = { ...menuItem, updatedAt: new Date().toISOString() }
    } else {
      data.menus.push({ 
        ...menuItem, 
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      })
    }
    
    // Save to file
    await fs.writeFile(filePath, JSON.stringify(data, null, 2))
    
    return {
      success: true,
      data: menuItem
    }
  } catch (error) {
    console.error('Error saving menu:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to save menu'
    })
  }
})
