package mx.gob.slp.baseadminweb.configuration.security;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;

import java.net.URI;

@Configuration
@ConditionalOnProperty(prefix = "app.cognito", name = "enabled", havingValue = "true")
public class CognitoClientConfig {

    @Bean(destroyMethod = "close")
    CognitoIdentityProviderClient cognitoIdentityProviderClient(CognitoProperties properties) {
        var builder = CognitoIdentityProviderClient.builder()
                .region(Region.of(properties.getRegion()));

        if (properties.usesLocalEndpoint()) {
            builder.endpointOverride(URI.create(properties.getEndpoint()))
                    .credentialsProvider(StaticCredentialsProvider.create(
                            AwsBasicCredentials.create("test", "test")));
        } else {
            builder.credentialsProvider(DefaultCredentialsProvider.create());
        }

        return builder.build();
    }
}