// composables/useWaitForAuth.ts
import { getAuth } from 'firebase/auth';

export const useWaitForAuth = async (): Promise<void> => {
  // Skip when Nuxt is rendering on the server (or in build)
  if (import.meta.server) return;

  const auth = getAuth();

  // If already signed‑in, nothing to wait for
  if (auth.currentUser) return;

  // Otherwise wait (or timeout after 5 s)
  await Promise.race([
    new Promise<void>((resolve) => {
      const off = auth.onAuthStateChanged((user) => {
        if (user) {
          off();
          resolve();
        }
      });
    }),
    new Promise<void>((_, reject) =>
      setTimeout(() => reject(new Error('Auth timeout')), 5000)
    ),
  ]);
};
