import { createRouter, createWebHistory } from 'vue-router'
import adminRouter from './admin'
import merchantRouter from './merchant'
import userRouter from './user'
import { authRoutes } from './auth'
import { createAuthGuard, createAfterGuard, createErrorHandler } from './guards'

// 导入错误页面
const ErrorPage = () => import('@/views/ErrorPage.vue')
const Chat=()=>import('@/views/chat.vue')

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 根路径重定向到登录页
    {
      path: '/',
      redirect: '/login',
    },
    // 错误页面路由
    {
      path: '/error',
      name: 'Error',
      component: ErrorPage,
      meta: {
        title: '系统错误',
        requiresAuth: false,
        layout: 'blank',
      },
    },
    // 认证相关路由
    ...authRoutes,
    // 现有的业务路由
    {
      path: '/admin',
      children: [...adminRouter.options.routes],
      meta: {
        requiresAuth: true,
        allowedRoles: ['admin'],
      },
    },
    {
      path: '/merchant',
      children: [...merchantRouter.options.routes],
      meta: {
        requiresAuth: true,
        allowedRoles: ['manager'],
      },
    },
    {
      path: '/user',
      children: [...userRouter.options.routes],
      meta: {
        requiresAuth: true,
        allowedRoles: ['customer'],
      },
    },
    // 404 页面 - 重定向到错误页面
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      redirect: (to) => {
        return {
          path: '/error',
          query: {
            type: '404',
            message: '页面未找到',
            path: to.path,
          },
        }
      },
    },
    {
      path: '/chat',
      name: 'Chat',
      component: Chat,
      meta: {
        title: '聊天系统'
      }
    }
  ],
})

// 注册全局前置守卫
router.beforeEach(createAuthGuard())

// 注册全局后置守卫
router.afterEach(createAfterGuard())

// 注册路由错误处理
router.onError(createErrorHandler())

export default router
