export interface ResolvableHomeUser {
  id?: string;
  displayName?: string;
  homeSignalServerUrl?: string;
}

export interface ResolvedSignalIdentity {
  userId: string;
  token: string;
  displayName: string;
  homeSignalServerUrl?: string;
}

/**
 * Resolve the identity (oder id + session token) used to `identify` on a signal
 * server.
 *
 * Order of precedence:
 *  1. The per-signal-server credential (the authoritative source for both home
 *     and provisioned foreign servers).
 *  2. The legacy single-session token store, reconstructed with the home user's
 *     identity. This keeps `identify` working for sessions restored from disk
 *     that pre-date the per-signal credential store (otherwise the client never
 *     authenticates and the user appears alone in every room).
 *
 * Foreign servers are never reconstructed from the legacy token: their account
 * id is the provisioned id, which only the per-signal credential carries.
 */
export function resolveSignalIdentity(
  credential: { userId: string; token: string; displayName: string } | null,
  legacyToken: { token: string } | null,
  homeUser: ResolvableHomeUser | null | undefined
): ResolvedSignalIdentity | null {
  if (credential) {
    return {
      userId: credential.userId,
      token: credential.token,
      displayName: credential.displayName,
      homeSignalServerUrl: homeUser?.homeSignalServerUrl
    };
  }

  if (legacyToken && homeUser?.id) {
    return {
      userId: homeUser.id,
      token: legacyToken.token,
      displayName: homeUser.displayName ?? '',
      homeSignalServerUrl: homeUser.homeSignalServerUrl
    };
  }

  return null;
}
