'use client';
// packages/ui/src/routing/hooks/useRedirectGuard.next.ts
/**
 * @fileoverview Next.js Redirect Guard Hook
 * @description Determines redirect state before render. Prevents content flash.
 *
 * @version 0.0.3
 * @since 0.0.1
 * @author AMBROISE PARK Consulting
 */
import { useMemo } from 'react';
import { isClient, FEATURE_STATUS } from '@donotdev/core';
import { useAuthConfig } from '@donotdev/core';
import { useLocation } from './useLocation.next';
import { useAuthSafe } from '../../utils/useAuthSafe';
/**
 * Hook that checks if redirect should happen before render
 *
 * Prevents content flash by determining redirect state synchronously.
 * Returns safe defaults on server (SSR-safe).
 *
 * @param options - Redirect guard configuration
 * @returns Redirect guard state
 */
export function useRedirectGuard(options = {}) {
    const { auth, redirectTo: customRedirectTo, condition } = options;
    // Hooks must be called unconditionally (Rules of Hooks)
    const location = useLocation();
    const authConfig = useAuthConfig();
    const user = useAuthSafe('user');
    const can = useAuthSafe('can');
    const status = useAuthSafe('status');
    // Determine redirect state
    const redirectState = useMemo(() => {
        // SSR-safe: return safe defaults on server
        if (!isClient()) {
            return {
                shouldRedirect: false,
                redirectTo: null,
                isChecking: false,
            };
        }
        // Only INITIALIZING = still checking. DEGRADED/ERROR/READY = auth resolved (proceed with current user)
        if (status === FEATURE_STATUS.INITIALIZING) {
            return {
                shouldRedirect: false,
                redirectTo: null,
                isChecking: true,
            };
        }
        // Custom condition provided
        if (condition) {
            const shouldRedirect = condition(user, status);
            return {
                shouldRedirect,
                redirectTo: shouldRedirect ? customRedirectTo || null : null,
                isChecking: false,
            };
        }
        // Use auth config to determine redirect
        if (auth !== false && auth !== undefined) {
            if (!can) {
                return {
                    shouldRedirect: false,
                    redirectTo: null,
                    isChecking: false,
                };
            }
            // Check if user can navigate to this route
            if (!can.navigate(auth)) {
                let targetRoute = null;
                // Authentication failure (not logged in)
                if (typeof auth === 'object' && auth.required && !user) {
                    // Check if we have OAuth parameters that need to be preserved
                    const hasOAuthParams = location.search?.includes('code=') ||
                        location.search?.includes('state=') ||
                        location.search?.includes('error=');
                    if (hasOAuthParams) {
                        targetRoute = `${authConfig.authRoute}${location.search}`;
                    }
                    else {
                        targetRoute = authConfig.authRoute;
                    }
                }
                // Authorization failure (wrong role)
                else if (typeof auth === 'object' && auth.role) {
                    targetRoute = authConfig.roleRoute;
                }
                // Authorization failure (wrong tier)
                else if (typeof auth === 'object' && auth.tier) {
                    targetRoute = authConfig.tierRoute;
                }
                // Fallback
                else {
                    targetRoute = authConfig.roleRoute;
                }
                return {
                    shouldRedirect: true,
                    redirectTo: customRedirectTo || targetRoute,
                    isChecking: false,
                };
            }
        }
        // No redirect needed
        return {
            shouldRedirect: false,
            redirectTo: null,
            isChecking: false,
        };
    }, [
        auth,
        status,
        user,
        can,
        condition,
        customRedirectTo,
        location.search,
        authConfig.authRoute,
        authConfig.roleRoute,
        authConfig.tierRoute,
    ]);
    return redirectState;
}
