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

async function fetchMenuData() {
  return withDbRetries(
    async () => {
      const menuItems = await MenuItem.findAll({
        order: [['order_id', 'ASC']],
        include: [{
          model: MenuItem,
          as: 'submenu',
          required: false,
          order: [['order_id', 'ASC']]
        }]
      });
      return buildMenuStructure(menuItems);
    },
    { attempts: 3, baseDelayMs: 200 }
  );
}

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,
      order_id: item.order_id,
      pageTitle: item.page_title,
      image: item.image,
      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;
