// import type { HttpContext } from '@adonisjs/core/http'

import RestaurantMenu from '#models/restaurant_menu'
import { HttpContext } from '@adonisjs/core/http'
import logger from '@adonisjs/core/services/logger'

export default class RestaurantMenusController {
  /**
   * Retrieve all restaurant menus.
   *
   * @returns An array of all restaurant menus.
   */
  async getAll() {
    const menus = await RestaurantMenu.query().preload('items', (itemsQuery) => {
      itemsQuery.preload('category')
    })
    return menus
  }
  /**
   * Retrieve a restaurant menu.
   *
   * @bodyParam id number The id of the menu to retrieve.
   * @returns The retrieved menu.
   */
  async getOne({ request }: HttpContext) {
    const id = request.body().id
    try {
      const menu = await RestaurantMenu.query()
        .where('id', id)
        .preload('items', (itemsQuery) => {
          itemsQuery.preload('category')
        })
        .first()
      return menu
    } catch (error) {
      logger.error('Menu retrieval failed: %s', error)
    }
  }

  /**
   * Create a restaurant menu.
   *
   * @bodyParam name string The name of the menu.
   * @bodyParam description string The description of the menu.
   * @returns The created menu.
   */
  async create({ request, auth }: HttpContext) {
    const data = request.body()
    try {
      const menu = await RestaurantMenu.create(data)
      logger.info('Menu created: %s by %s', menu.name, auth.getUserOrFail().email)
      return menu
    } catch (error) {
      logger.error('Menu creation failed: %s', error)
    }
  }

  /**
   * Update a restaurant menu.
   *
   * @bodyParam id number. The id of the menu to update.
   * @bodyParam name string. The new name of the menu.
   */
  async update({ request, auth }: HttpContext) {
    const data = request.body()
    try {
      const menu = await RestaurantMenu.find(data.id)
      menu?.merge(data)
      await menu?.save()
      logger.info('Menu updated: %s by %s', menu?.name, auth.getUserOrFail().email)
    } catch (error) {
      logger.error('Menu update failed: %s', error)
    }
  }

  /**
   * Delete a restaurant menu.
   *
   * @bodyParam id number. The id of the menu to delete.
   */
  async delete({ request, auth, response }: HttpContext) {
    const id = request.body().id
    try {
      const menu = await RestaurantMenu.find(id)
      if (!menu) {
        return response.notFound({ message: 'Menu not found' })
      }

      // Detach all menu items before deleting the menu
      await menu.related('items').detach()
      await menu.delete()
      logger.info('Menu deleted: %s by %s', menu.name, auth.getUserOrFail().email)
      return response.ok({ message: 'Menu deleted' })
    } catch (error) {
      logger.error('Menu deletion failed: %s', error)
      return response.internalServerError({ message: 'Menu deletion failed' })
    }
  }
}
