const { MenuItem } = require('../models');

async function fetchMenuData() {
  try {
    const menuItems = await MenuItem.findAll({
      order: [['order_id', 'ASC']],
      include: [{
        model: MenuItem,
        as: 'submenu',
        required: false,
        order: [['order_id', 'ASC']]
      }]
    });

    const menuData = buildMenuStructure(menuItems);

    return menuData;
  } catch (error) {
    console.error('There was a problem fetching the menu data:', error);
    return [];
  }
}

function buildMenuStructure(menuItems) {
  const menu = [];
  const itemMap = {};

  menuItems.forEach(item => {
    itemMap[item.id] = {
      id: item.id,
      name: item.name,
      link: item.link,
      component: item.component,
      showInMenu: item.show_in_menu,
      requiresAuth: item.requires_auth,
      orderId: item.order_id,
      pageTitle: item.page_title,
      submenu: []
    };
  });

  menuItems.forEach(item => {
    if (item.parent_id) {
      if (itemMap[item.parent_id]) {
        itemMap[item.parent_id].submenu.push(itemMap[item.id]);
      }
    } else {
      menu.push(itemMap[item.id]);
    }
  });

  menu.sort((a, b) => a.orderId - b.orderId);
  menu.forEach(item => {
    item.submenu.sort((a, b) => a.orderId - b.orderId);
  });

  return menu;
}

module.exports = fetchMenuData;
