"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformAWSAuthMechanismOptions = transformAWSAuthMechanismOptions;
const mongodb_connection_string_url_1 = require("mongodb-connection-string-url");
function transformAWSAuthMechanismOptions({ uri, clientOptions, }) {
    let connectionString;
    try {
        connectionString = new mongodb_connection_string_url_1.ConnectionString(uri);
    }
    catch {
        return { uri, clientOptions };
    }
    const searchParams = connectionString.typedSearchParams();
    if ((clientOptions.authMechanism ?? searchParams.get('authMechanism')) !==
        'MONGODB-AWS') {
        return { uri, clientOptions };
    }
    const username = clientOptions.auth?.username ??
        decodeURIComponent(connectionString.username);
    const password = clientOptions.auth?.password ??
        decodeURIComponent(connectionString.password);
    const authMechProps = new mongodb_connection_string_url_1.CommaAndColonSeparatedRecord(searchParams.get('authMechanismProperties') ?? '');
    const sessionToken = clientOptions.authMechanismProperties?.AWS_SESSION_TOKEN ??
        authMechProps.get('AWS_SESSION_TOKEN');
    if (username || password || sessionToken) {
        connectionString.username = '';
        connectionString.password = '';
        authMechProps.delete('AWS_SESSION_TOKEN');
        if (authMechProps.size === 0) {
            searchParams.delete('authMechanismProperties');
        }
        else {
            searchParams.set('authMechanismProperties', authMechProps.toString());
        }
        const programmaticAuthMechProps = { ...clientOptions.authMechanismProperties };
        delete programmaticAuthMechProps.AWS_SESSION_TOKEN;
        programmaticAuthMechProps.AWS_CREDENTIAL_PROVIDER ?? (programmaticAuthMechProps.AWS_CREDENTIAL_PROVIDER = () => {
            const creds = {
                accessKeyId: username,
                secretAccessKey: password,
                sessionToken: sessionToken || undefined,
            };
            return Promise.resolve(creds);
        });
        clientOptions = {
            ...clientOptions,
            auth: undefined,
            authMechanismProperties: programmaticAuthMechProps,
        };
    }
    return { uri: connectionString.toString(), clientOptions };
}
//# sourceMappingURL=aws-auth-compat.js.map