/**
 * router/index.ts
 *
 * Automatic routes for `./src/pages/*.vue`
 */

// Composables
import { createRouter, createWebHistory } from 'vue-router/auto';
import { setupLayouts } from 'virtual:generated-layouts';
import { NavigationGuardNext, RouteLocation } from 'vue-router';
import prefetch from './middlewares/prefetch';
import auth from './middlewares/auth';

const middlewares = [/*auth, */ prefetch];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  extendRoutes: setupLayouts,
});

router.beforeEach(
  async (to: RouteLocation, from: RouteLocation, next: NavigationGuardNext) => {
    if (!from.name || from.path !== to.path) {
      for await (const middleware of middlewares) {
        await middleware(to, from, next);
      }
    }
    next();
  },
);

export default router;
