export class ProvisionUsernameCollisionError extends Error {
  constructor(
    readonly serverUrl: string,
    readonly attemptedUsernames: readonly string[]
  ) {
    super(`Could not provision account on ${serverUrl}`);
    this.name = 'ProvisionUsernameCollisionError';
  }
}

export function shortHomeUserId(homeUserId: string): string {
  return homeUserId.replace(/-/g, '').slice(0, 6)
    .toLowerCase();
}

export function buildProvisionUsernameCandidates(
  preferredUsername: string,
  homeUserId: string
): string[] {
  const trimmed = preferredUsername.trim();

  if (!trimmed) {
    return [];
  }

  const candidates = [trimmed];
  const suffix = shortHomeUserId(homeUserId);

  if (suffix && !trimmed.endsWith(`-${suffix}`)) {
    candidates.push(`${trimmed}-${suffix}`);
  }

  return [...new Set(candidates)];
}
