import { stripLocaleFromPathname } from '@/i18n/routing';

const AUTH_REDIRECT_KEY = 'authRedirect';

export function storeAuthRedirectFromPath(pathWithOptionalLocale: string) {
  if (typeof window === 'undefined') return;
  const path = stripLocaleFromPathname(pathWithOptionalLocale);
  if (!path || path === '/login' || path === '/register') return;
  sessionStorage.setItem(AUTH_REDIRECT_KEY, path);
}

export function consumeAuthRedirect(): string | null {
  if (typeof window === 'undefined') return null;
  const path = sessionStorage.getItem(AUTH_REDIRECT_KEY);
  if (path) sessionStorage.removeItem(AUTH_REDIRECT_KEY);
  return path;
}

/** Dashboard (or a stored share-link / post-auth path). Consume once — never inside useAuth.login() or registerTrial. */
export function appPathAfterAuth(): string {
  return consumeAuthRedirect() ?? '/today';
}

/**
 * After login() on invite pages only. Multi-org already went to /select-organization.
 * Do not use useEnterAppWhenAuthenticated on invite pages.
 */
export function navigateIntoAppIfOrgSelected(
  replace: (href: string) => void,
  organizationCount: number,
) {
  if (organizationCount > 1) return;
  replace(appPathAfterAuth());
}
