import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('./pages/HomePage.vue'),
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('./pages/SearchResult.vue'),
  },
  {
    path: '/result/:id',
    name: 'result-detail',
    component: () => import('./pages/ResultDetail.vue'),
  },
  {
    path: '/admin/login',
    name: 'admin-login',
    component: () => import('./pages/admin/AdminLogin.vue'),
  },
  {
    path: '/admin',
    component: () => import('./pages/admin/AdminLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: '/admin/dashboard',
      },
      {
        path: 'dashboard',
        name: 'admin-dashboard',
        component: () => import('./pages/admin/AdminDashboard.vue'),
      },
      {
        path: 'cloud-configs',
        name: 'admin-cloud-configs',
        component: () => import('./pages/admin/CloudConfig.vue'),
      },
      {
        path: 'cleanup',
        name: 'admin-cleanup',
        component: () => import('./pages/admin/Cleanup.vue'),
      },
      {
        path: 'system',
        name: 'admin-system',
        component: () => import('./pages/admin/SystemConfig.vue'),
      },
      {
        path: 'save-records',
        name: 'admin-save-records',
        component: () => import('./pages/admin/SaveRecords.vue'),
      },
    ],
  },
  {
    path: '/user/login',
    name: 'user-login',
    component: () => import('./pages/user/UserLogin.vue'),
  },
  {
    path: '/user/dashboard',
    name: 'user-dashboard',
    component: () => import('./pages/user/UserDashboard.vue'),
  },
  {
    path: '/user',
    redirect: '/user/login',
  },
]

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

router.beforeEach((to, _from, next) => {
  const token = localStorage.getItem('admin_token')
  if (to.meta.requiresAuth && !token) {
    next('/admin/login')
  } else {
    next()
  }
})

export default router
