import { defineNuxtRouteMiddleware, navigateTo } from '#app';

export default defineNuxtRouteMiddleware(async () => {
  console.log('👤 Guest middleware: Checking if user is already authenticated...');

  // Skip on server-side during development
  if (process.server && process.env.NODE_ENV === 'development') {
    console.log('⏭️ Skipping guest check on server-side during development');
    return;
  }

  try {
    console.log('🔍 Checking if user is already authenticated...');
    
    // The $fetch will automatically send the user_session cookie
    const session = await $fetch<{ user: any } | null>('/api/auth/session').catch(() => null);

    if (session && session.user) {
      console.log('✅ User already authenticated, redirecting to dashboard');
      return navigateTo('/dashboard');
    } else {
      console.log('ℹ️ No session found, staying on login page');
      return;
    }
  } catch (error) {
    console.log('ℹ️ Auth check failed (expected for login), staying on login page');
    return;
  }
});
