import { createRouter, createWebHashHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes = [
  { path: '/',             name: 'Dashboard',  component: () => import('@/pages/DashboardPage.vue') },
  { path: '/servers',      name: 'Servers',    component: () => import('@/pages/ServersPage.vue') },
  { path: '/terminal',     name: 'Terminal',    component: () => import('@/pages/TerminalPage.vue') },
  { path: '/files',        name: 'Files',      component: () => import('@/pages/FilesPage.vue') },
  { path: '/push',         name: 'Push',       component: () => import('@/pages/PushPage.vue') },
  { path: '/scripts',      name: 'Scripts',    component: () => import('@/pages/ScriptsPage.vue') },
  { path: '/credentials',  name: 'Credentials',component: () => import('@/pages/CredentialsPage.vue') },
  { path: '/schedules',    name: 'Schedules',  component: () => import('@/pages/SchedulesPage.vue') },
  { path: '/retries',      name: 'Retries',    component: () => import('@/pages/RetriesPage.vue') },
  { path: '/commands',     name: 'Commands',   component: () => import('@/pages/CommandsPage.vue') },
  { path: '/alerts',       name: 'Alerts',     component: () => import('@/pages/AlertsPage.vue') },
  { path: '/audit',        name: 'Audit',      component: () => import('@/pages/AuditPage.vue') },
  { path: '/settings',     name: 'Settings',   component: () => import('@/pages/SettingsPage.vue') },
  { path: '/login',        name: 'Login',      component: () => import('@/pages/LoginPage.vue'), meta: { public: true } },
]

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

/** 懒加载 chunk 失败时提示强刷（多因 index 与 assets 哈希不一致） */
router.onError((err, to) => {
  const msg = err?.message || ''
  if (
    msg.includes('Failed to fetch dynamically imported module')
    || msg.includes('Importing a module script failed')
    || msg.includes('error loading dynamically imported module')
  ) {
    const w = window as Window & { $snackbar?: (text: string, color?: string) => void }
    w.$snackbar?.(`页面「${String(to.name || to.path)}」加载失败，请 Ctrl+F5 强制刷新`, 'error')
  }
})

// Auth guard — restore session from HttpOnly refresh cookie when needed
router.beforeEach(async (to) => {
  const auth = useAuthStore()
  if (!auth.bootstrapped) {
    await auth.tryRestoreSession()
  }
  if (!to.meta.public && !auth.isLoggedIn) {
    return { name: 'Login', query: { redirect: to.fullPath } }
  }
  if (to.name === 'Login' && auth.isLoggedIn) {
    return { name: 'Dashboard' }
  }
})

export default router
