import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const monitorBlockedPaths = ['/dashboard', '/vendor/load', '/generate']

function getHomePath() {
  const userStore = useUserStore()
  return userStore.isMonitorMode() ? '/task/chain' : '/dashboard'
}

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/LoginView.vue'),
      meta: { public: true },
    },
    {
      path: '/',
      component: () => import('@/layouts/AdminLayout.vue'),
      redirect: () => getHomePath(),
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/dashboard/DashboardView.vue'),
          meta: { title: '首页' },
        },
        {
          path: 'task/chain',
          name: 'TaskChainList',
          component: () => import('@/views/task/TaskChainList.vue'),
          meta: { title: '任务链管理' },
        },
        {
          path: 'task/chain/:code',
          name: 'TaskChainDetail',
          component: () => import('@/views/task/TaskChainDetail.vue'),
          meta: { title: '任务链详情' },
        },
        {
          path: 'elevator',
          name: 'ElevatorList',
          component: () => import('@/views/elevator/ElevatorList.vue'),
          meta: { title: '提升机管理' },
        },
        {
          path: 'station/queue',
          name: 'StationQueueView',
          component: () => import('@/views/station/StationQueueView.vue'),
          meta: { title: '站点排队' },
        },
        {
          path: 'resource/extension',
          name: 'ExtensionResourceView',
          component: () => import('@/views/resource/ExtensionResourceView.vue'),
          meta: { title: '拓展资源' },
        },
        {
          path: 'vendor/load',
          name: 'VendorLoadView',
          component: () => import('@/views/vendor/VendorLoadView.vue'),
          meta: { title: '厂商负载' },
        },
        {
          path: 'generate',
          name: 'TaskGenerate',
          component: () => import('@/views/generate/TaskGenerateView.vue'),
          meta: { title: '任务生成' },
        },
        {
          path: 'docs/exception',
          name: 'ExceptionDocs',
          component: () => import('@/views/docs/ExceptionDocsView.vue'),
          meta: { title: '异常处理' },
        },
      ],
    },
  ],
})

router.beforeEach((to, _from, next) => {
  const userStore = useUserStore()
  const token = localStorage.getItem('token')
  if (!to.meta.public && !token) {
    next('/login')
  } else if (to.path === '/login' && token) {
    next(getHomePath())
  } else if (!to.meta.public && userStore.isMonitorMode() && monitorBlockedPaths.includes(to.path)) {
    next('/task/chain')
  } else {
    next()
  }
})

export default router
