import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'

// 业务模块路由配置（仅作参考，实际路由由后端动态生成）
export { businessRoutes, userPermissions, goodsPermissions, orderPermissions } from './modules/business'

// 静态路由
const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404' }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/layout/index.vue'),
    meta: { title: '个人中心' },
    children: [
      {
        path: '',
        component: () => import('@/views/profile/index.vue'),
        meta: { title: '个人中心' }
      }
    ]
  },
  {
    path: '/password',
    name: 'Password',
    component: () => import('@/layout/index.vue'),
    meta: { title: '修改密码' },
    children: [
      {
        path: '',
        component: () => import('@/views/password/index.vue'),
        meta: { title: '修改密码' }
      }
    ]
  }
]

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

// 白名单路由
const whiteList = ['/login', '/404']

// 标记动态路由是否已加载
let dynamicRoutesLoaded = false

// 重置动态路由状态（供外部调用）
export function resetRouter() {
  dynamicRoutesLoaded = false
}

// 路由守卫
router.beforeEach(async (to, _from, next) => {
  const token = getToken()
  
  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const userStore = useUserStore()
      const permissionStore = usePermissionStore()
      
      // 检查动态路由是否已加载
      if (dynamicRoutesLoaded) {
        next()
      } else {
        try {
          // 获取用户信息（如果还没有）
          if (!userStore.userInfo) {
            await userStore.getUserInfo()
          }
          // 生成动态路由
          const accessRoutes = await permissionStore.generateRoutes()
          // 添加动态路由
          accessRoutes.forEach(route => {
            router.addRoute(route)
          })
          // 添加 404 兜底路由
          router.addRoute({ path: '/:pathMatch(.*)*', redirect: '/404' })
          // 标记动态路由已加载
          dynamicRoutesLoaded = true
          next({ ...to, replace: true })
        } catch (error) {
          // 获取用户信息失败，清除 token 并跳转登录页
          dynamicRoutesLoaded = false
          userStore.logout()
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    // 重置动态路由标记
    dynamicRoutesLoaded = false
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

export default router
