import { createRouter as createVueRouter, createWebHistory<%- microfrontend ? ', type RouteRecordRaw' : '' %> } from 'vue-router';
<%_ if (microfrontend) { _%>
import { loadRemote } from '@module-federation/<%- clientBundlerVite ? '' : 'enhanced/' %>runtime';
<%_ } _%>

const Home = () => import('@/core/home/home.vue');
const Error = () => import('@/core/error/error.vue');
<%_ if (generateUserManagement) { _%>
import account from '@/router/account';
<%_ } _%>
import admin from '@/router/admin';
import entities from '@/router/entities';
import pages from '@/router/pages';

export const createRouter = () => createVueRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/forbidden',
      name: 'Forbidden',
      component: Error,
      meta: { error403: true }
    },
    {
      path: '/not-found',
      name: 'NotFound',
      component: Error,
      meta: { error404: true }
    },
<%_ if (generateUserManagement) { _%>
    ...account,
<%_ } _%>
    ...admin,
<%_ if (exposeMicrofrontend) { _%>
    // Load entities route exposed by microfrontend
<%_ } _%>
    <%- exposeMicrofrontend ? '// ' : '' %>entities,
    ...pages
  ]
});

const router = createRouter();

<%_ if (microfrontend) { _%>
export const lazyRoutes = Promise.all([
  <%_ for (const remote of microfrontends) { _%>
  loadRemote<any>('<%- remote.moduleFederationName %>/entities-router')
    .then(<%- remote.moduleFederationName %>Router => {
      router.addRoute(<%- remote.moduleFederationName %>Router.default as RouteRecordRaw);
      return <%- remote.moduleFederationName %>Router.default;
    }).catch(error => {
      console.log(`Error loading <%- remote.moduleFederationName %> menus. Make sure it's up. ${error}`);
    }),
  <%_ } _%>
]);

<%_ } _%>
router.beforeResolve(async (to, from, next) => {
  if (!to.matched.length) {
<%_ if (microfrontend) { _%>
    await lazyRoutes;
    if (router.resolve(to.fullPath).matched.length > 0) {
      next({ path: to.fullPath });
      return;
    }

<%_ } _%>
    next({ path: '/not-found' });
    return;
  }
  next();
});

export default router;
