import type { User } from '../../../../shared-kernel';

export const SESSION_EXPIRED_ERROR_CODE = 'SESSION_EXPIRED';

function normalizeServerUrl(serverUrl: string): string {
  return serverUrl.trim().replace(/\/+$/, '');
}

export function collectSessionTokenLookupUrls(
  user: Pick<User, 'homeSignalServerUrl'>,
  activeServerUrl?: string | null
): string[] {
  const urls = new Set<string>();

  if (activeServerUrl?.trim()) {
    urls.add(normalizeServerUrl(activeServerUrl));
  }

  if (user.homeSignalServerUrl?.trim()) {
    urls.add(normalizeServerUrl(user.homeSignalServerUrl));
  }

  return [...urls];
}

export function hasValidSessionTokenForUrls(
  urls: readonly string[],
  getToken: (serverUrl: string) => string | null
): boolean {
  return urls.some((url) => !!getToken(url));
}

export function hasValidPersistedSession(
  user: Pick<User, 'homeSignalServerUrl'>,
  activeServerUrl: string | null | undefined,
  getToken: (serverUrl: string) => string | null,
  hasAnyValidToken?: () => boolean
): boolean {
  const preferredUrls = collectSessionTokenLookupUrls(user, activeServerUrl);

  if (preferredUrls.length > 0 && hasValidSessionTokenForUrls(preferredUrls, getToken)) {
    return true;
  }

  return hasAnyValidToken?.() ?? false;
}
