import { createRouter, createWebHistory } from 'vue-router'
import UserModule from '@/modules/01_user/router'
import AdminModule from '@/modules/02_admin/router'
import { getRole, getToken, login } from '@/services/KeyCloakService'

const history = createWebHistory(import.meta.env.BASE_URL)
const router = createRouter({
  history,
  routes: [
    {
      path: '/',
      name: 'UserModule',
      component: () => import('@/views/MainLayout.vue'),
      beforeEnter: async (_to, _from, next) => {
        const token = await getToken()

        if (token) return next()

        await login(async () => {
          if (await getToken()) return next()
          return next('/')
        })
      },
      children: [...UserModule],
      meta: { statusAccount: false },
    },
    {
      path: '/admin',
      name: 'AdminModule',
      component: () => import('@/views/MainLayout.vue'),
      beforeEnter: async (_to, _from, next) => {
        const token = await getToken()

        if (token) {
          const roles = getRole()

          if (token && roles.includes('admin')) {
            return next()
          }

          return next('/')
        }

        await login(async () => {
          const token = await getToken()
          const roles = getRole()

          if (token && roles.includes('admin')) {
            return next()
          }

          return next('/')
        })
      },
      meta: { statusAccount: true },
      children: [...AdminModule],
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/ErrorNotFoundPage.vue'),
    },
  ],
})

export default router
