import { to as tos } from 'await-to-js';
import router from './router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken } from '@/utils/auth';
import { isPathMatch } from '@/utils/validate';
import { useUserStore } from '@/store/modules/user';
import { ElMessage } from 'element-plus/es';
import { getCurrentSite, SITE_ROUTES } from '@/utils/siteConfig';

NProgress.configure({ showSpinner: false });
const whiteList = ['/login', '/register', '/social-callback', '/register*', '/register/*', '/index', '/'];

const isWhiteList = (path: string) => {
  return whiteList.some((pattern) => isPathMatch(pattern, path));
};

// 获取主站完整 URL（用于跨域跳转）
function getMainSiteUrl(path: any) {
  if (import.meta.env.PROD) {
    return `https://www.yoe365.com${path}`;
  } else {
    return `http://localhost:5101${path}`;
  }
}

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const site = getCurrentSite();
  const allowedPaths = SITE_ROUTES[site];
  const host = window.location.hostname;
  const port = window.location.port;
  if (getToken()) {
    const [err] = await tos(useUserStore().getInfo());
    if (err) {
      await useUserStore().logout();
      ElMessage.error(err);
      window.location.href = getMainSiteUrl('/index');
      NProgress.done();
    } else {
      if (!allowedPaths.includes(to.path)) {
        console.warn(`[${site}] 禁止访问 ${to.path}`);
        window.location.href = getMainSiteUrl('/index');
        NProgress.done();
      } else {
        next();
        NProgress.done();
      }
    }
  } else {
    // 没有token
    if (isWhiteList(to.path)) {
      if (host == 'www.yoe365.com' || port == '5101') {
        next();
      } else {
        window.location.href = getMainSiteUrl(to.path);
      }
      NProgress.done();
    } else {
      window.location.href = getMainSiteUrl('/index');
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
