export default defineNuxtRouteMiddleware(async (to) => {
  // Skip on server-side rendering
  if (import.meta.server) return;

  // Skip if no auth requirements or roles specified
  if (!to.meta.roles) {
    return;
  }

  console.log('[AUTHORIZATION] Checking route access for:', to.path, 'Required roles:', to.meta.roles);

  try {
    // Get current session data with groups
    const sessionData = await $fetch('/api/auth/session') as any;
    
    if (!sessionData.authenticated || !sessionData.user) {
      console.log('[AUTHORIZATION] User not authenticated, redirecting to login');
      return navigateTo('/login');
    }

    // Get required roles for this route
    const requiredRoles = Array.isArray(to.meta.roles) ? to.meta.roles : [to.meta.roles];
    const userGroups = sessionData.groups || [];

    // Check if user has any of the required roles
    const hasRequiredRole = requiredRoles.some(role => userGroups.includes(role));

    if (!hasRequiredRole) {
      console.log('[AUTHORIZATION] Access denied. User groups:', userGroups, 'Required roles:', requiredRoles);
      
      // Store the error in nuxtApp to show toast on redirect
      const nuxtApp = useNuxtApp();
      nuxtApp.payload.authError = `Access denied. This page requires one of the following roles: ${requiredRoles.join(', ')}`;
      
      // Redirect to dashboard instead of login since user is authenticated
      return navigateTo('/dashboard');
    }

    // Store auth state in nuxtApp for use by components
    const nuxtApp = useNuxtApp();
    if (!nuxtApp.payload.data) {
      nuxtApp.payload.data = {};
    }
    nuxtApp.payload.data.authState = {
      user: sessionData.user,
      authenticated: sessionData.authenticated,
      groups: sessionData.groups || []
    };

    console.log('[AUTHORIZATION] Access granted for route:', to.path);
  } catch (error) {
    console.error('[AUTHORIZATION] Error checking route access:', error);
    
    // If session check fails, redirect to login
    return navigateTo('/login');
  }
});
