import { defineNuxtRouteMiddleware, navigateTo } from '#app';
import type { RouteLocationNormalized } from 'vue-router';
import { useAuth } from '~/composables/useAuth'; 

export default defineNuxtRouteMiddleware(async (to: RouteLocationNormalized) => {
  console.log('🛡️ Auth middleware triggered for:', to.path);

  // Check for bypass flag (from keyboard shortcut)
  if (process.client) {
    const bypassFlag = sessionStorage.getItem('bypassRootRedirect');
    if (bypassFlag === 'true' && to.path === '/') {
      console.log('🔑 Bypass flag detected - allowing root access');
      sessionStorage.removeItem('bypassRootRedirect');
      return;
    }
  }

  // Redirect root path to LoginPage
  if (to.path === '/') {
    console.log('🔄 Redirecting from root to LoginPage');
    return navigateTo('/LoginPage', { replace: true });
  }

  // Allow the login page to handle its own checks without redirection loops
  if (to.path === '/LoginPage') {
    console.log('⏭️ Allowing access to LoginPage');
    return;
  }
  
  // On server-side, skip auth check - let client handle it
  if (process.server) {
    console.log('⏭️ Server-side: Skipping auth check (will verify on client)');
    return;
  }

  // CLIENT-SIDE ONLY from here
  
  // Check for the authentication signal from a successful login redirect
  const isAuthRedirect = to.query.authenticated === 'true';

  if (isAuthRedirect) {
    console.log('⏳ Processing new login session...');
    
    // Give browser time to process the cookie from redirect
    await new Promise(resolve => setTimeout(resolve, 100));
    
    try {
      const { checkAuth } = useAuth();
      console.log('🔍 Checking authentication after redirect...');
      
      let user = await checkAuth();
      
      // Retry up to 3 times if cookie not available yet
      let retries = 0;
      while (!user && retries < 3) {
        console.log(`⚠️ Cookie not available yet, retry ${retries + 1}/3...`);
        await new Promise(resolve => setTimeout(resolve, 200));
        user = await checkAuth();
        retries++;
      }
      
      if (user) {
        console.log('✅ User authenticated after redirect:', user.name || user.email);
        // Remove query parameter and allow access
        return navigateTo({ path: to.path, query: {} }, { replace: true });
      } else {
        console.log('❌ No session after retries, redirecting to login');
        return navigateTo('/LoginPage');
      }
    } catch (authError) {
      console.error('❌ Auth check failed after redirect:', authError);
      return navigateTo('/LoginPage');
    }
  }

  // Normal auth check for protected routes
  try {
    const { checkAuth } = useAuth();
    console.log('🔍 Checking authentication status...');
    
    const user = await checkAuth(); 

    if (user) {
      console.log('✅ User is authenticated:', user.name || user.email);
      return;
    } else {
      console.log('❌ No valid session found, redirecting to login');
      return navigateTo('/LoginPage');
    }
  } catch (error) {
    console.error('❌ Auth middleware error:', error);
    console.log('🔄 Redirecting to login due to error');
    return navigateTo('/LoginPage');
  }
});