import { configureOidc } from '@/services/authentikAuth'
import { getConfig } from '@/services/siteConfig'
import type { Config } from '@/types/Config'
import type { OidcAuth } from 'vue-oidc-client/vue3'
import { createRouter, createWebHistory } from 'vue-router'

const oidcAuth: OidcAuth = await configureOidc().then((value: OidcAuth): OidcAuth => value)
const config: Config = await getConfig().then((value: Config | null): Config => value !== null ? value : {} as Config)

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/HomeView.vue')
    },
    {
      path: '/blessing-power',
      name: 'blessing-power',
      component: () => import('@/views/BlessingPowerView.vue')
    },
    {
      path: '/fellow-power',
      name: 'fellow-power',
      component: () => import('@/views/FellowPowerView.vue')
    },
    {
      path: '/intimacy-power',
      name: 'intimacy-power',
      component: () => import('@/views/IntimacyPowerView.vue')
    },
    {
      path: '/test',
      name: 'test',
      component: () => import('@/views/TestView.vue')
    },

    {
      path: '/login',
      name: 'login',
      meta: {
        authName: oidcAuth.authName
      },
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/admin',
      name: 'admin',
      meta: {
        authName: oidcAuth.authName
      },
      component: () =>
        hasRole('admin') ? import('@/views/Admin.vue') : import('@/views/NoAccess.vue')
    }
  ]
})

const hasRole = (role: string) => {
  if (config.oidcProjectID === undefined) {
    throw new Error('Config was not loaded')
  }
  const roles = oidcAuth.userProfile[`urn:zitadel:iam:org:project:${config.oidcProjectID}:roles`] as Array<any>
  if (!roles) {
    return false
  }
  return roles.find(r => r[role])
}

oidcAuth!.useRouter(router)

export default router
