import { createRouter, createWebHistory, type RouteLocationNormalized } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import LoginView from '@/views/LoginView.vue'
import { useAuthStore } from '@/stores/auth'
import MyAccountView from '@/views/MyAccountView.vue'
import { createClassroomComplianceRoutes } from '@/apps/classroom_compliance/router'

/**
 * Ensures that only authenticate users can access a route.
 * @param to The route the user is navigating to.
 * @returns True if the user is authenticated. Otherwise, returns a redirect to
 * the login page, so the user can login to access the page.
 */
export function enforceAuth(to: RouteLocationNormalized) {
  const authStore = useAuthStore()
  if (authStore.state) return true
  console.log(to.fullPath, to.path)
  return '/login?next=' + encodeURIComponent(to.path)
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: HomeView,
    },
    {
      path: '/login',
      component: LoginView,
    },
    {
      path: '/my-account',
      component: MyAccountView,
      beforeEnter: [enforceAuth],
    },
    createClassroomComplianceRoutes(),
    {
      path: '/admin-dashboard',
      component: () => import('@/views/AdminDashboardView.vue'),
      beforeEnter: [enforceAuth],
    },
  ],
})

export default router
