const routes = [
  // Public
  { path: '/login', component: '/page/auth/login.html', layout: 'auth' },
  { path: '/callback/:provider', component: '/page/auth/callback.html', layout: 'auth' },

  // Dashboard (Default Layout)
  {
    path: '/',
    layout: 'default',
    meta: { auth: true },
    component: '/page/dashboard/index.html'
  },

  // Role Management
  { path: '/roles', component: '/page/sys/role/index.html', layout: 'default', meta: { auth: true, perm: '*' } },

  // Settings Management
  { path: '/settings', component: '/page/sys/settings.html', layout: 'default', meta: { auth: true, perm: '*' } },

  // User System
  { path: '/profile', component: '/page/user/profile.html', layout: 'default', meta: { auth: true } },
  {
    path: '/users',
    component: '/page/sys/user/index.html',
    layout: 'default',
    meta: { auth: true, perm: '*' }
  },

  // OAuth Management
  { path: '/oauth/apps', component: '/page/sys/oauth/index.html', layout: 'default', meta: { auth: true, perm: '*' } },
  { path: '/oauth/providers', component: '/page/sys/oauth/providers.html', layout: 'default', meta: { auth: true, perm: '*' } },

  // Errors
  { path: '/403', component: '/page/403.html' },
  { path: '*', component: '/page/404.html' }
]

export default ({ $mod }) => ({
  routes: routes,
  beforeEnter: async (to, from, next) => {
    const isAuth = to.meta && to.meta.auth;
    const roles = to.meta && to.meta.roles; // Array of required roles
    const vbase = $mod.$auth

    if (isAuth) {
      if (!vbase.user) {
        try {
          await vbase.fetchUser();
        } catch (e) {
          vbase.logout('/login?redirect=' + encodeURIComponent(to.fullPath));
          return false;
        }
      }

      // Permission Check
      if (to.meta.perm) {
        if (!vbase.PermAdmin(to.meta.perm)) {
          console.warn('Access denied: requires permission', to.meta.perm);
          $mod.$router.push('/403');
          return false;
        }
      }
    }

    next();
  }
})
