import { createRouter, createWebHistory } from 'vue-router'
import MainLayout from '@/layouts/MainLayout.vue'
import Login from '@/views/Login.vue'
import Dashboard from '@/views/Dashboard.vue'
import Clients from '@/views/Clients.vue'
import Tunnels from '@/views/Tunnels.vue'
import Hosts from '@/views/Hosts.vue'
import IPRules from '@/views/IPRules.vue'
import RequestIPs from '@/views/RequestIPs.vue'
import Users from '@/views/Users.vue'
import Settings from '@/views/Settings.vue'

const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    component: MainLayout,
    redirect: '/dashboard',
    children: [
      { path: 'dashboard', component: Dashboard },
      { path: 'clients', component: Clients },
      { path: 'tunnels', component: Tunnels },
      { path: 'hosts', component: Hosts },
      { path: 'security/ip-rules', component: IPRules },
      { path: 'security/request-ips', component: RequestIPs },
      { path: 'users', component: Users },
      { path: 'settings', component: Settings },
    ],
  },
]

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

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path !== '/login' && !token) {
    next('/login')
  } else if (to.path === '/login' && token) {
    next('/dashboard')
  } else {
    next()
  }
})

export default router
