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 })

// Auth guard
router.beforeEach((to) => {
  const auth = useAuthStore()
  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
