import routes from "@/routes";

/**
 * Navigates to the auth page using server-side navigation (full page reload)
 * This ensures that server-side redirects work properly
 * 
 * @param redirectUrl - URL to redirect to after successful authentication
 * @param forceServerSide - Whether to force server-side navigation even if not needed
 */
export const navigateToAuth = (redirectUrl?: string, forceServerSide = false): void => {
  // If forceServerSide is true or we detect that we need server-side navigation,
  // use window.location for a full page reload
  if (forceServerSide) {
    const authUrl = routes.client.auth();
    const url = redirectUrl ? `${authUrl}?redirectUrl=${encodeURIComponent(redirectUrl)}` : authUrl;
    window.location.href = url;
  } else {
    // Otherwise, let the application handle it with client-side routing
    // This is handled by the router configuration
    const authUrl = routes.client.auth();
    // Use history.pushState for client-side navigation
    window.history.pushState({}, '', redirectUrl ? `${authUrl}?redirectUrl=${encodeURIComponent(redirectUrl)}` : authUrl);
    // Dispatch a popstate event to notify the router of the change
    window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
  }
};
