// middleware/village-tick.global.ts
export default defineNuxtRouteMiddleware(async (to) => {
  // We only run this logic on the client-side after navigation.
  if (process.server) {
    return;
  }

  const { isAuthenticated, initialized } = useAuth();
  
  // Helper function to wait for auth initialization, with a timeout.
  const waitForAuth = () => {
    return new Promise((resolve) => {
      if (initialized.value) {
        return resolve(true);
      }
      const timeout = setTimeout(() => {
        unwatch();
        resolve(true); // Resolve even if timeout, so middleware doesn't block
      }, 5000);
      const unwatch = watch(initialized, (newValue) => {
        if (newValue) {
          clearTimeout(timeout);
          unwatch();
          resolve(true);
        }
      });
    });
  };
  
  // Wait for auth to be initialized
  await waitForAuth();

  // If user is authenticated, trigger the village tick
  if (isAuthenticated.value) {
    const api = useApi();
    try {
      // We must await the call to ensure it completes before a new navigation can cancel it.
      await api('/api/village/tick', { method: 'POST' });
    } catch (e) {
      // Even if we don't wait, a catch block is good practice in case the api call itself throws an error.
      console.error('[Village Middleware] Failed to trigger village tick:', e);
    }
  }
});

