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;
  
  if (!isAuthRequired) {
    return;
  }

  try {
    // Check Directus auth first
    const { fetchUser, setUser } = useDirectusAuth();
    const directusUser = useDirectusUser();
    
    if (!directusUser.value) {
      try {
        const user = await fetchUser();
        setUser(user.value);
      } catch (error) {
        // Directus auth failed, continue to check custom Keycloak auth
      }
    }

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

    // Check custom Keycloak auth via session API
    try {
      const sessionData = await $fetch('/api/auth/session') as any;
      if (sessionData.authenticated && sessionData.user) {
        // User authenticated with Keycloak
        return;
      }
    } catch (error) {
      // Session check failed, continue to redirect
    }

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