// /middleware/auth.global.ts
export default defineNuxtRouteMiddleware(async (to) => {
  const { isAuthenticated, initialized, updateUser } = useAuth();
  const { visitCalled } = useVisitTracker();
  const api = useApi();

  // Helper function to wait for auth initialization, with a timeout.
  const waitForAuth = () => {
    return new Promise((resolve) => {
      // If already initialized, resolve immediately.
      if (initialized.value) {
        return resolve(true);
      }
      
      // Set a timeout to prevent waiting indefinitely
      const timeout = setTimeout(() => {
        console.warn('[Auth Middleware] Waited 5 seconds for auth, but it did not initialize. Proceeding anyway.');
        unwatch();
        resolve(false);
      }, 5000);

      // Watch for the initialized value to change to true.
      const unwatch = watch(initialized, (newValue) => {
        if (newValue) {
          clearTimeout(timeout);
          unwatch();
          resolve(true);
        }
      });
    });
  };

  // Only run the waiting logic on the client-side
  if (process.client) {
    await waitForAuth();
  } else if (!initialized.value) {
    // On the server, if not initialized, we cannot wait.
    return;
  }
  
  // --- Daily Visit Registration ---
  // This logic runs once per application load on the client-side for authenticated users.
  if (process.client && isAuthenticated.value && !visitCalled.value) {
    visitCalled.value = true; // Set flag immediately to prevent race conditions
    try {
      // Get the client's current date in "YYYY-MM-DD" format.
      const gameDay = new Date().toISOString().slice(0, 10);
      
      const updatedUser = await api('/api/user/visit', { 
        method: 'POST',
        body: { gameDay }
      });
      if (updatedUser) {
        updateUser(updatedUser);
      }
    } catch (e: any) {
      console.error("[Auth Middleware] Failed to register daily visit.", e);
    }
  }

  // if the user is authenticated and tries to access /login, redirect to home
  if (isAuthenticated.value && to.path === '/login') {
    return navigateTo('/', { replace: true });
  }

  // if the user is not authenticated and tries to access any page other than public routes, redirect to /login
  const publicRoutes = ['/login', '/register'];
  if (!isAuthenticated.value && !publicRoutes.includes(to.path)) {
    return navigateTo('/login', { replace: true });
  }
});