import { createRouter, createWebHistory } from 'vue-router'

import { useAdminSessionStore } from '@/stores/adminSession'
import { useSessionStore } from '@/stores/session'
import { getAccessToken, getLoginPath } from '@/shared/utils/authStorage'
import { accountRoutes } from './accountRoutes'
import { adminRoutes } from './adminRoutes'
import { isMobileHost, isMobileDevice, getMobilePath, getPcPath } from './mobileHost'
import { mobileRoutes } from './mobileRoutes'
import { publicRoutes } from './publicRoutes'
import { sellerRoutes } from './sellerRoutes'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    ...adminRoutes,
    ...mobileRoutes,
    ...publicRoutes,
    ...accountRoutes,
    ...sellerRoutes,
  ],
})

router.beforeEach(async (to) => {
  const isMobile = isMobileHost() || isMobileDevice()

  if (isMobile) {
    const targetPath = getMobilePath(to.path)
    if (to.path !== targetPath) {
      return { path: targetPath, query: to.query, hash: to.hash }
    }
  } else {
    const targetPath = getPcPath(to.path)
    if (to.path !== targetPath) {
      return { path: targetPath, query: to.query, hash: to.hash }
    }
  }

  if (to.meta.requiresAuth) {
    const session = useSessionStore()
    session.syncFromStorage()
    const hasToken = !!session.token
    if (!hasToken) {
      const loginPath = getLoginPath('user', to.path)
      return { path: loginPath, query: { redirect: to.fullPath } }
    }
    // 优化: 只有当用户信息未加载时才调用 loadMe
    if (!session.phone) {
      try {
        await session.loadMe()
      } catch {
        const loginPath = getLoginPath('user', to.path)
        return { path: loginPath, query: { redirect: to.fullPath } }
      }
    }
  }

  if (to.meta.requiresRealname) {
    const session = useSessionStore()
    session.syncFromStorage()
    const loginPath = getLoginPath('user', to.path)
    const realnamePath = to.path.startsWith('/m') ? '/m/realname' : '/realname'

    // 优化: 只有当状态未知或未验证时才重新加载
    if (session.realnameStatus !== 'verified') {
      // 如果没有 phone 信息，说明用户数据未加载
      if (!session.phone) {
        try {
          await session.loadMe()
        } catch {
          if (!getAccessToken('user')) {
            return { path: loginPath, query: { redirect: to.fullPath } }
          }
        }
      }

      // 再次检查实名状态
      if (session.realnameStatus !== 'verified') {
        return { path: realnamePath, query: { redirect: to.fullPath } }
      }
    }
  }

  const adminSession = useAdminSessionStore()
  adminSession.syncFromStorage()
  if (to.path === '/admin/login' && adminSession.token) {
    return '/admin/dashboard'
  }
  if (to.meta.requiresAdmin) {
    if (!adminSession.token) {
      return '/admin/login'
    }
    if (adminSession.permissions.length === 0) {
      try {
        await adminSession.loadMe()
      } catch {
        // 权限加载失败，仍然允许访问（降级为无权限状态）
      }
    }
  }
  return true
})

export default router
