import { useAuthStore } from '@/stores/auth'
export default defineNuxtRouteMiddleware((to, from) => {
  //TODO: remove logs
  console.log('🔍 Middleware ejecutado')
  console.log('📦 to.meta:', to.meta)
  const AUTH_ROLES = {
    ANON: 0,
    SHOP_USER: 1,
    COOP_MANAGER: 2,
    SITE_ADMIN: 3,
  }
  const authStore = useAuthStore()
  const userRole = authStore.role
  console.log('👤 Rol actual:', userRole)

  const authority = to.meta?.auth?.authority as keyof typeof AUTH_ROLES
  const requiredLevel = AUTH_ROLES[authority]
  //const required = to.meta.auth?.authority
  console.log('⚠️ Autoridad requerida:', authority, requiredLevel)

  
  // Check if user is connected first
  // if (!store.getters['user/user'].isAuthenticated) return redirect('/login')

  // Get authorizations for matched routes (with children routes too)

  const userLevel = AUTH_ROLES[userRole as keyof typeof AUTH_ROLES]
  console.log('🧮 userLevel:', userLevel, 'requiredLevel:', requiredLevel)

  console.log('[Auth Middleware]', {
    to: to.path,
    meta: to.meta,
    userRole: authStore.role,
    requiredLevel,
    userLevel,
  })
  
  if (userLevel < requiredLevel) {
    console.log('🚫 Bloqueando acceso - redirigiendo a /login')
    return navigateTo('/login')
  }

})