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

export const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    { path: '/login', component: () => import('@/views/LoginView.vue') },
    { path: '/register', component: () => import('@/views/RegisterView.vue') },
    {
      path: '/admin',
      component: () => import('@/layouts/AdminLayout.vue'),
      meta: { requiresAuth: true },
      children: [
        { path: '', redirect: '/admin/dashboard' },
        { path: 'dashboard', component: () => import('@/views/admin/DashboardView.vue') },
        { path: 'banks', component: () => import('@/views/admin/BanksView.vue') },
        { path: 'questions', component: () => import('@/views/admin/QuestionsView.vue') },
        { path: 'taxonomy', component: () => import('@/views/admin/TaxonomyView.vue') },
        { path: 'papers', component: () => import('@/views/admin/PapersView.vue') },
        { path: 'classes', component: () => import('@/views/admin/ClassesView.vue') },
        { path: 'reports', component: () => import('@/views/admin/ReportsView.vue') },
        { path: 'users', component: () => import('@/views/admin/UsersView.vue') },
        { path: 'permissions', component: () => import('@/views/admin/PermissionsView.vue') },
        { path: 'settings', component: () => import('@/views/admin/SettingsView.vue') },
        { path: 'logs', component: () => import('@/views/admin/LogsView.vue') },
      ],
    },
    {
      path: '/quiz',
      component: () => import('@/layouts/QuizLayout.vue'),
      meta: { requiresAuth: true },
      children: [
        { path: '', component: () => import('@/views/app/ResourcesView.vue') },
        { path: 'wrong-questions', component: () => import('@/views/app/WrongQuestionsView.vue') },
        { path: ':attemptId', component: () => import('@/views/app/QuizView.vue') },
      ],
    },
    { path: '/', redirect: '/quiz' },
  ],
})

router.beforeEach(async (to) => {
  const auth = useAuthStore()
  if (auth.token && !auth.user) {
    await auth.loadMe().catch(() => auth.clearSession())
  }
  if (to.meta.requiresAuth && !auth.isAuthed) {
    return '/login'
  }
  if (to.path === '/login' && auth.isAuthed) {
    return '/quiz'
  }
})
