import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'

// 路由表 -- 映射现有 Flask 页面路由
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false, title: '登录' }
  },
  {
    path: '/',
    name: 'Platform',
    component: () => import('@/views/Platform.vue'),
    meta: { requiresAuth: true, title: '运行维护平台' }
  },
  // 问题排查 -- 独立布局（无侧边栏）
  // Index.vue 会根据 /api/health 的 offline_mode 自动切换界面
  {
    path: '/troubleshoot',
    name: 'Troubleshoot',
    component: () => import('@/views/troubleshoot/Index.vue'),
    meta: { requiresAuth: true, title: '问题排查' }
  },
  {
    path: '/troubleshoot/logs',
    name: 'TroubleshootLogs',
    component: () => import('@/views/troubleshoot/Logs.vue'),
    meta: { requiresAuth: true, title: '操作日志' }
  },
  // 服务监测 -- 侧边栏布局
  {
    path: '/service-monitor',
    component: () => import('@/layouts/MonitorLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'MonitorIndex',
        component: () => import('@/views/service-monitor/Index.vue'),
        meta: { activeMenu: 'targets', title: '监测目标' }
      },
      {
        path: 'targets',
        name: 'MonitorTargets',
        component: () => import('@/views/service-monitor/Targets.vue'),
        meta: { activeMenu: 'manage', title: '目标管理', requiresAdmin: true }
      },
      {
        path: 'reports',
        name: 'MonitorReports',
        component: () => import('@/views/service-monitor/Reports.vue'),
        meta: { activeMenu: 'reports', title: '巡检报告' }
      },
      {
        path: 'report/:reportId',
        name: 'MonitorReportDetail',
        component: () => import('@/views/service-monitor/ReportDetail.vue'),
        meta: { activeMenu: 'reports', title: '报告详情' }
      },
      {
        path: 'statistics',
        name: 'MonitorStatistics',
        component: () => import('@/views/service-monitor/Statistics.vue'),
        meta: { activeMenu: 'statistics', title: '监测统计' }
      },
      {
        path: 'schedule',
        name: 'MonitorSchedule',
        component: () => import('@/views/service-monitor/Schedule.vue'),
        meta: { activeMenu: 'schedule', title: '定时任务' }
      },
      {
        path: 'notification',
        name: 'MonitorNotification',
        component: () => import('@/views/service-monitor/Notification.vue'),
        meta: { activeMenu: 'notification', title: '通知配置', requiresAdmin: true }
      },
      {
        path: 'run/:targetId',
        name: 'MonitorRun',
        component: () => import('@/views/service-monitor/Run.vue'),
        meta: { activeMenu: 'targets', title: '巡检执行', requiresAdmin: true }
      },
      {
        path: 'compare/:reportIdA/:reportIdB',
        name: 'MonitorCompare',
        component: () => import('@/views/service-monitor/Compare.vue'),
        meta: { activeMenu: 'reports', title: '报告对比' }
      },
      {
        path: 'logs',
        name: 'MonitorLogs',
        component: () => import('@/views/service-monitor/Logs.vue'),
        meta: { activeMenu: 'logs', title: '操作日志' }
      },
    ]
  },
  // 服务管理 -- 侧边栏布局
  {
    path: '/service-manage',
    component: () => import('@/layouts/ManageLayout.vue'),
    meta: { requiresAuth: true, requiresAdmin: true },
    children: [
      {
        path: '',
        redirect: '/service-manage/authorization'
      },
      {
        path: 'authorization',
        name: 'ManageAuthorization',
        component: () => import('@/views/service-manage/Authorization.vue'),
        meta: { activeMenu: 'authorization', title: '服务授权' }
      },
      {
        path: 'upgrade',
        name: 'ManageUpgrade',
        component: () => import('@/views/service-manage/Upgrade.vue'),
        meta: { activeMenu: 'upgrade', title: '服务升级' }
      },
      {
        path: 'info',
        name: 'ManageInfo',
        component: () => import('@/views/service-manage/Info.vue'),
        meta: { activeMenu: 'info', title: '服务信息' }
      },
      {
        path: 'logs',
        name: 'ManageLogs',
        component: () => import('@/views/service-manage/Logs.vue'),
        meta: { activeMenu: 'logs', title: '操作日志' }
      },
    ]
  },
  // 404 兜底
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: { requiresAuth: false, title: '页面不存在' }
  }
]

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

// 路由守卫
router.beforeEach(async (to, _from, next) => {
  const userStore = useUserStore()

  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 运行维护平台` : '运行维护平台'

  // 不需要认证的页面直接放行
  if (to.meta.requiresAuth === false) {
    // 已登录用户访问登录页，跳转首页
    if (to.name === 'Login' && userStore.isLoggedIn) {
      next({ path: '/' })
      return
    }
    next()
    return
  }

  // 需要认证但未登录
  if (!userStore.isLoggedIn) {
    // 尝试从后端恢复会话
    if (!userStore.hasCheckedAuth) {
      try {
        await userStore.fetchUserInfo()
        // 恢复成功，继续检查权限
      } catch {
        // 会话失效，跳转登录
        next({ name: 'Login', query: { next: to.fullPath } })
        return
      }
    } else {
      // 已检查过但未登录
      next({ name: 'Login', query: { next: to.fullPath } })
      return
    }
  }

  // 管理员权限检查
  if (to.meta.requiresAdmin && !userStore.isAdmin) {
    next({ path: '/' })
    return
  }

  next()
})

export default router
