// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.identity;

import com.azure.core.credential.AccessToken;
import com.azure.core.credential.TokenCredential;
import com.azure.core.credential.TokenRequestContext;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.logging.ClientLogger;
import com.azure.identity.implementation.IdentityClient;
import com.azure.identity.implementation.IdentityClientBuilder;
import com.azure.identity.implementation.IdentityClientOptions;
import com.azure.identity.implementation.MsalToken;
import com.azure.identity.implementation.VisualStudioCacheAccessor;
import com.azure.identity.implementation.util.LoggingUtil;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Enables authentication to Azure Active Directory using data from Visual Studio Code
 */
public class VisualStudioCodeCredential implements TokenCredential {
    private final IdentityClient identityClient;
    private final AtomicReference<MsalToken> cachedToken;
    private final String cloudInstance;
    private static final ClientLogger LOGGER = new ClientLogger(VisualStudioCodeCredential.class);

    /**
     * Creates a public class VisualStudioCodeCredential implements TokenCredential with the given tenant and
     * identity client options.
     *
     * @param tenantId the tenant ID of the application
     * @param identityClientOptions the options for configuring the identity client
     */
    VisualStudioCodeCredential(String tenantId, IdentityClientOptions identityClientOptions) {

        IdentityClientOptions options = (identityClientOptions == null ? new IdentityClientOptions()
                                                 : identityClientOptions);
        String tenant;

        VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor();
        Map<String, String> userSettings = accessor.getUserSettingsDetails();

        cloudInstance = userSettings.get("cloud");
        if (CoreUtils.isNullOrEmpty(options.getAuthorityHost())) {
            options.setAuthorityHost(accessor.getAzureAuthHost(cloudInstance));
        }

        if (!CoreUtils.isNullOrEmpty(tenantId)) {
            tenant = tenantId;
        } else {
            tenant = userSettings.getOrDefault("tenant", "common");
        }

        identityClient = new IdentityClientBuilder()
                .tenantId(tenant)
                .clientId("aebc6443-996d-45c2-90f0-388ff96faa56")
                .identityClientOptions(options)
                .build();

        this.cachedToken = new AtomicReference<>();
    }

    @Override
    public Mono<AccessToken> getToken(TokenRequestContext request) {
        return Mono.defer(() -> {
            if (cachedToken.get() != null) {
                return identityClient.authenticateWithPublicClientCache(request, cachedToken.get().getAccount())
                           .onErrorResume(t -> Mono.empty());
            } else {
                return Mono.empty();
            }
        }).switchIfEmpty(
            Mono.defer(() -> identityClient.authenticateWithVsCodeCredential(request, cloudInstance)))
                   .map(msalToken -> {
                       cachedToken.set(msalToken);
                       return (AccessToken) msalToken;
                   })
            .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request))
            .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(),
                request, error));
    }
}

@@ -269,16 +269,79 @@
 ontext;%0A
+import com.azure.core.exception.ClientAuthenticationException;%0A
 import c
@@ -1302,24 +1302,270 @@
 al.class);%0A%0A
+    private static final String TROUBLESHOOTING = %22VisualStudioCodeCredential is affected by known issues. See https://aka.ms/azsdk/java/identity/troubleshoot#troubleshoot-visualstudiocodecredential-authentication-issues for more information.%22;%0A%0A
     /**%0A    
@@ -3796,16 +3796,482 @@
 error -%3E
+ %7B%0A                Throwable other = null;%0A                if (error instanceof CredentialUnavailableException) %7B%0A                    other = new CredentialUnavailableException(TROUBLESHOOTING, error);%0A%0A                %7D else if (error instanceof ClientAuthenticationException) %7B%0A                    other = new ClientAuthenticationException(TROUBLESHOOTING, null, error);%0A                %7D else %7B%0A                    other = error;%0A                %7D%0A               
  Logging
@@ -4356,16 +4356,20 @@
         
+    
 request,
@@ -4369,22 +4369,37 @@
 equest, 
-error)
+other);%0A            %7D
 );%0A    %7D

update exception message (#30246)