import { createRouter, createWebHistory } from 'vue-router';
import AuthPage from '../components/authentication/AuthPage.vue';
import MainPage from '../views/mainpage/index.vue';

// 路由守卫：检查是否登录 - 优化版
const requireAuth = (to, from, next) => {
  // 更可靠的登录状态检查
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
  const hasUserInfo = !!localStorage.getItem('userInfo');
  
  if (isLoggedIn && hasUserInfo) {
    next();
  } else {
    // 清除无效的登录状态
    localStorage.removeItem('isLoggedIn');
    next('/');
  }
};

const routes = [
  {
    path: '/',
    name: 'Auth',
    component: AuthPage,
    beforeEnter: (to, from, next) => {
      const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
      const hasUserInfo = !!localStorage.getItem('userInfo');
      
      if (isLoggedIn && hasUserInfo) {
        next('/main');
      } else {
        next();
      }
    }
  },
  {
    path: '/main',
    name: 'Main',
    component: MainPage,
    beforeEnter: requireAuth
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
];

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

// 全局路由守卫，处理可能的登录状态异常
router.beforeEach((to, from, next) => {
  // 对所有需要授权的路由进行检查
  if (to.matched.some(record => record.beforeEnter === requireAuth)) {
    requireAuth(to, from, next);
  } else {
    next();
  }
});

export default router;
