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

import { useUserStore } from '@/store';

export default function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const userStore = useUserStore();
    if (!to.meta.requiresAuth) {
      next();
      NProgress.done();
      return;
    }
    if (userStore.accessToken) {
      next();
      NProgress.done();
    } else {
      if (to.name === 'Login') {
        next();
        NProgress.done();
        return;
      }

      next({
        name: 'Login',
      });
      NProgress.done();
    }
  });
}
