import { createRouter, createWebHistory } from 'vue-router'
import { tokenManager } from '@/api/client'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
      meta: { guest: true }
    },
    {
      path: '/',
      component: () => import('@/views/LayoutView.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'dashboard',
          component: () => import('@/views/DashboardView.vue')
        },
        {
          path: 'users',
          name: 'users',
          component: () => import('@/views/user/UserListView.vue')
        },
        {
          path: 'users/:id',
          name: 'user-detail',
          component: () => import('@/views/user/UserDetailView.vue')
        },
        {
          path: 'users/:id/bookmarks',
          name: 'user-bookmarks',
          component: () => import('@/views/bookmark/UserBookmarksView.vue')
        }
      ]
    }
  ]
})

router.beforeEach((to, _from, next) => {
  const token = tokenManager.getAccessToken()
  const isAuthenticated = !!token && !tokenManager.isTokenExpired()

  if (to.meta.requiresAuth && !isAuthenticated) {
    next({ name: 'login' })
  } else if (to.meta.guest && isAuthenticated) {
    next({ name: 'dashboard' })
  } else {
    next()
  }
})

export default router

