import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { NOT_FOUND_ROUTE, REDIRECT_ROUTE } from '@/router/routes'
import { getUserInfo, signinRedirect, signoutRedirect } from '@/utils/oidc/index.js'

export function createPermissionGuard(router) {
  const userStore = useUserStore()
  const permissionStore = usePermissionStore()
  router.beforeEach(async(to, from, next) => {
    const oidcUser = await getUserInfo()
    if (oidcUser) {
      const hasRoutes = !!permissionStore.permissionRoutes.length
      if (hasRoutes) {
        next()
      } else {
        try {
          const { clientRoleList } = oidcUser.profile
          const { VITE_CLIENT_ID } = import.meta.env
          const { roleId } = clientRoleList.find((item) => {
            return item.clientId === VITE_CLIENT_ID
          })
          // await userStore.getUserInfo()
          // const routes = await permissionStore.generateRoutes(roleId)
          const routes = await permissionStore.generateRoutesMock()
          routes.forEach((item) => {
            router.addRoute(item)
          })
          router.addRoute(NOT_FOUND_ROUTE)
          router.addRoute(REDIRECT_ROUTE)
          next({ ...to, replace: true })
        } catch (error) {
          signinRedirect()
        }
      }
    } else {
      if (to.path === '/login') {
        next()
      } else {
        signinRedirect()
      }
    }
  })
}
