/**
   * This method takes a VSO_DEPLOYMENT context and returns the VSO context that has the correct PAT
   *
   * @param originalContext the VSO_DEPLOYMENT context to use to generate the PAT
   * @param authenticationProvider the provider used to create the original context
   * @param tokenDescription the description to use for the generated PAT
   * @return a new VSO context object
   */
  public ServerContext createVsoContext(
      ServerContext originalContext,
      VsoAuthenticationProvider authenticationProvider,
      String tokenDescription) {
    // If the context is a VSO_DEPLOYMENT, then we can generate the PAT and create a new context
    // Otherwise, throw an exception
    if (originalContext == null || originalContext.getType() != ServerContext.Type.VSO_DEPLOYMENT) {
      throw new IllegalArgumentException("originalContext must be a VSO_DEPLOYMENT context");
    }
    if (authenticationProvider == null) {
      throw new IllegalArgumentException("authenticationProvider must be set");
    }

    // generate PAT
    final AuthenticationResult result = authenticationProvider.getAuthenticationResult();
    final PersonalAccessTokenFactory patFactory = new PersonalAccessTokenFactoryImpl(result);

    final String accountName = UrlHelper.getVSOAccountName(originalContext.getUri());
    final Account account = AccountLookupOperation.getAccount(result, accountName);

    if (account != null) {
      // TODO: handle case where session token cannot be created
      SessionToken sessionToken =
          patFactory.createSessionToken(
              tokenDescription,
              Arrays.asList(TokenScope.CODE_READ, TokenScope.CODE_WRITE, TokenScope.CODE_MANAGE),
              account.getAccountId());
      // create a VSO context with session token (remove the original client and allow that to be
      // recreated)
      final AuthenticationInfo finalAuthenticationInfo =
          AuthHelper.createAuthenticationInfo(
              originalContext.getUri().toString(), result, sessionToken);
      final ServerContext newContext =
          new ServerContextBuilder(originalContext)
              .type(ServerContext.Type.VSO)
              .authentication(finalAuthenticationInfo)
              .buildWithClient(null);
      return newContext;
    }

    logger.debug("Account not found: " + accountName);
    return null;
  }