import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import Login from '../views/Login.vue';
import NoPermission from '../views/common/NoPermission.vue';
import SSOCallback from '../views/SSOCallback.vue';
import { useUserStore } from '../stores/user';
import { usePermissionStore } from '../stores/permission';

const constantRoutes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/callback',
    name: 'SSOCallback',
    component: SSOCallback
  },
  {
    path: '/no-permission',
    name: 'NoPermission',
    component: NoPermission
  },
  {
    path: '/',
    redirect: '/monitor/dashboard'
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
});

const whiteList = ['/login', '/no-permission', '/callback'];

const getFirstAccessiblePath = (routes: RouteRecordRaw[]): string | null => {
  for (const route of routes) {
    if (route.children && route.children.length > 0) {
      const childPath = getFirstAccessiblePath(route.children);
      if (childPath) {
        if (childPath.startsWith('/')) {
          return childPath;
        }
        return `${route.path}/${childPath}`.replace('//', '/');
      }
    }
    if (typeof route.path === 'string' && route.path) {
      return route.path;
    }
  }
  return null;
};

router.beforeEach(async (to, _from, next) => {
  const userStore = useUserStore();
  const permissionStore = usePermissionStore();
  
  const token = localStorage.getItem('token');
  
  if (token) {
    if (to.path === '/login') {
      // Only redirect to home if routes are ready; otherwise allow login page
      if (permissionStore.addRoutes.length > 0) {
        next({ path: '/' });
      } else {
        next();
      }
      return;
    } else {
      if (userStore.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        // 这里简化：如果没有拉取过菜单，则拉取
        // 实际上应该先拉取 user info 获取 roles，再拉取 menus
        // 我们 assume login sets token, and first nav fetches menus
        
        try {
            // Note: In a real app we'd call userStore.getInfo() here
            // For now, we just assume we have a token and need to fetch routes
            // Using a flag or checking permissions length
            if (permissionStore.addRoutes.length === 0) {
                 try {
                     console.log('Fetching access routes...');
                     const accessRoutes = await permissionStore.generateRoutes();
                     console.log('Access routes generated:', accessRoutes);
                     
                     if (accessRoutes.length === 0) {
                        // 防止死循环：如果获取不到路由，说明权限配置有问题或者用户无权限
                        // 强制跳转到无权限页面
                        console.warn('No access routes found, redirecting to NoPermission page');
                        if (to.path !== '/no-permission') {
                            next('/no-permission');
                        } else {
                            next();
                        }
                        return;
                     }

                     // 动态添加可访问路由表
                     accessRoutes.forEach((route: any) => {
                        router.addRoute(route);
                     });
                     // hack方法 确保addRoutes已完成
                     next({ ...to, replace: true });
                 } catch (err) {
                     console.error('Error generating routes:', err);
                     // 出错也应该登出
                     userStore.logout();
                     next(`/login`);
                 }
            } else {
                if (to.matched.length === 0 && permissionStore.addRoutes.length > 0) {
                  const fallbackPath = getFirstAccessiblePath(permissionStore.addRoutes);
                  next(fallbackPath ? fallbackPath : '/');
                } else {
                  next();
                }
            }
        } catch (error) {
          userStore.logout();
          next(`/login?redirect=${to.path}`);
        }
      } else {
        next();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  }
});

export default router;
