import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { routes } from '@/plugins/routesLayout'
import { fetchCurrentUser } from '@/services/authSession'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes.filter((x) => x.meta !== undefined).map((x) => x.meta) as RouteRecordRaw[],
})

router.beforeEach(async (to) => {
  const requiresAuth = to.meta.requiresAuth === true
  const guestOnly = to.meta.guestOnly === true

  if (!requiresAuth && !guestOnly) {
    return true
  }

  let currentUser = null

  try {
    currentUser = await fetchCurrentUser()
  } catch {
    if (requiresAuth) {
      const query = to.fullPath !== '/' ? { redirect: to.fullPath } : {}

      return {
        name: 'Login',
        query,
        replace: true,
      }
    }

    return true
  }

  const isAuthenticated = currentUser !== null

  if (requiresAuth && !isAuthenticated) {
    const query = to.fullPath !== '/' ? { redirect: to.fullPath } : {}

    return {
      name: 'Login',
      query,
      replace: true,
    }
  }

  if (guestOnly && isAuthenticated) {
    return {
      name: 'Dashboard',
      replace: true,
    }
  }

  return true
})

export default router
