export default defineNuxtRouteMiddleware(async (to) => {
  // Skip auth for SSR
  if (import.meta.server) return;

  // Check if auth is required (default true unless explicitly set to false)
  const isAuthRequired = to.meta.auth !== false;
  
  try {
    // Check Directus auth first (more reliable)
    const { fetchUser, setUser } = useDirectusAuth();
    const directusUser = useDirectusUser();
    
    if (!directusUser.value) {
      try {
        const user = await fetchUser();
        setUser(user.value);
      } catch (error) {
        // Ignore directus auth errors
      }
    }

    if (directusUser.value) {
      // User authenticated with Directus
      return;
    }

    // Try Keycloak auth (only if we need it)
    if (isAuthRequired) {
      const keycloak = useKeycloak();
      
      // Only try to initialize if not already done
      if (!keycloak.isInitialized.value) {
        try {
          await keycloak.initKeycloak();
        } catch (error) {
          console.error('Keycloak init failed:', error);
        }
      }
      
      if (keycloak.isAuthenticated.value) {
        // User authenticated with Keycloak
        return;
      }
    }

    // No authentication found
    if (isAuthRequired) {
      // Redirect to login page
      return navigateTo('/login');
    }
  } catch (error) {
    console.error('Auth middleware error:', error);
    if (isAuthRequired) {
      return navigateTo('/login');
    }
  }
});
