import type { Router } from 'vue-router';
import NProgress from 'nprogress'; // progress bar

import { useAppStore, useUserStore } from '@/store';
import { WHITE_LIST, NOT_FOUND, DEFAULT_ROUTE_NAME } from '../constants';

export default function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach((to, from, next) => {
    if (WHITE_LIST.find((el) => el.name === to.name)) {
      next();
      NProgress.done();
      return;
    }

    const appStore = useAppStore();
    if (!appStore.appMenus.length) {
      const useStore = useUserStore();
      appStore.fetchServerMenu(useStore.role);
    }

    if (to.name === DEFAULT_ROUTE_NAME) {
      const destination = appStore.getMenuFirstRouter() || NOT_FOUND;
      console.log(destination);

      next(destination);
      NProgress.done();
      return;
    }

    if (!to.name || !appStore.validRoutes.includes(to.name as string)) {
      next(NOT_FOUND);
    } else {
      next();
    }

    NProgress.done();
  });
}
