'use client';

import { useEffect } from 'react';
import { useRouter } from '@/i18n/navigation';
import { appPathAfterAuth } from '@/lib/auth/postAuthRedirect';
import { useAuth } from '@/lib/hooks/useAuth';

/**
 * When a session already exists (or was just created on this page), enter the app.
 * Use on /login and /register only — not on invite pages, where a logged-in visitor
 * must still be able to finish accept before navigating.
 */
export function useEnterAppWhenAuthenticated() {
  const { user, isAuthReady, isLoading, organizations, currentOrganization } = useAuth();
  const router = useRouter();

  useEffect(() => {
    if (!isAuthReady || !user || isLoading) return;
    const orgReady = organizations.length <= 1 || currentOrganization;
    if (!orgReady) return;
    router.push(appPathAfterAuth());
  }, [isAuthReady, user, isLoading, organizations, currentOrganization, router]);
}
