/**
 * Redirects the user to the SSO login page with loop protection.
 *
 * This function checks a session storage timestamp to ensure that redirects
 * do not happen too frequently (blocking infinite redirect loops).
 */
export const redirectToSSO = () => {
  if (typeof window === 'undefined') return;

  const lastRedirect = sessionStorage.getItem('auth_redirect_timestamp');
  const now = Date.now();

  // Loop protection: allow redirect only if last one was > 5 seconds ago
  // or if no redirect has happened yet.
  if (!lastRedirect || now - parseInt(lastRedirect, 10) > 5000) {
    sessionStorage.setItem('auth_redirect_timestamp', now.toString());
    // const ssoLoginUrl = `${process.env.NEXT_PUBLIC_SSO_LOGIN_URL as string}?redirect_url=${window.location.href}`;

    const ltiSsoStart = `${process.env.NEXT_PUBLIC_API_BASE_URL as string}/sso/start?client_id=${process.env.NEXT_PUBLIC_CLIENT_ID as string}&redirect_url=${window.location.href}`;
    const ssoLoginUrl = `${process.env.NEXT_PUBLIC_SSO_LOGIN_URL as string}?redirect_url=${ltiSsoStart}`;
    window.location.href = ssoLoginUrl;
  } else {
    console.error('Redirect loop detected. Aborting redirect.');
  }
};
