import type { Pinia } from 'pinia'
import { PAGE_PERMISSIONS } from '~/lib/page-permission'

export default defineNuxtRouteMiddleware((to) => {
  if (to.meta.public) return

  const { $pinia } = useNuxtApp()
  if (import.meta.server) {
    const authStore = useUserStore($pinia as Pinia)
    // Check specific page permissions if defined in config
    const pagePermissions = PAGE_PERMISSIONS[to.path as keyof typeof PAGE_PERMISSIONS]
    if (pagePermissions) {
      const { checkRole } = useRBAC()
      if (!checkRole(pagePermissions)) {
        return navigateTo('/403')
      }
    }

    // Fallback to meta roles
    const requiredRoles = to.meta.roles as string[]
    if (requiredRoles && requiredRoles.length > 0) {
      // FIXME: change this dummy roles, when api is ready
      const userRoles = authStore.userRole
      // const userRoles = ['admisi']
      const hasRequiredRole = requiredRoles.some((role) => userRoles.includes(role))

      if (!hasRequiredRole) {
        return navigateTo('/403')
      }
    }
  }
})
