import type { Router, LocationQueryRaw } from 'vue-router';
import NProgress from 'nprogress'; // progress bar
import { isLogin } from '@/utils/auth';

export default function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    // const userStore = useUserStore();
    if (isLogin() && to.meta?.requiresAuth) {
      next();
      // if (userStore.role) {
      //   next();
      // } else {
      //   try {
      //     await userStore.info();
      //     next();
      //   } catch (error) {
      //     await userStore.logout();
      //     next({
      //       name: 'login',
      //       query: {
      //         redirect: to.name,
      //         ...to.query
      //       } as LocationQueryRaw
      //     });
      //   }
      // }
    } else {
      if (to.name === 'login' || to.name === 'notFound') {
        next();
        return;
      }
      if (!to.meta?.requiresAuth) {
        if (isLogin() || to.query.token !== '') {
          next();
        } else {
          next({ name: 'notFound' });
        }
        return;
      }
      next({
        name: 'login',
        query: {
          redirect: to.name,
          ...to.query
        } as LocationQueryRaw
      });
    }
  });
}
