// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
import { Logger } from "./logger.js";
export function processServiceAuthentication(sdkPackage) {
    let authClientParameter = undefined;
    for (const client of sdkPackage.clients) {
        for (const parameter of client.initialization.properties) {
            if (parameter.kind === "credential") {
                authClientParameter = parameter;
                break;
            }
        }
    }
    if (!authClientParameter) {
        return undefined;
    }
    if (authClientParameter.type.kind === "credential") {
        return processAuthType(authClientParameter.type);
    }
    const inputAuth = {};
    for (const authType of authClientParameter.type.variantTypes) {
        const auth = processAuthType(authType);
        if (auth?.ApiKey) {
            inputAuth.ApiKey = auth.ApiKey;
        }
        if (auth?.OAuth2) {
            inputAuth.OAuth2 = auth.OAuth2;
        }
    }
    return inputAuth;
}
function processAuthType(credentialType) {
    const scheme = credentialType.scheme;
    switch (scheme.type) {
        case "apiKey":
            return { ApiKey: { Name: scheme.name } };
        case "oauth2":
            return processOAuth2(scheme);
        case "http":
            {
                const schemeOrApiKeyPrefix = scheme.scheme;
                switch (schemeOrApiKeyPrefix) {
                    case "basic":
                        Logger.getInstance().warn(`${schemeOrApiKeyPrefix} auth method is currently not supported.`);
                        return undefined;
                    case "bearer":
                        return {
                            ApiKey: {
                                Name: "Authorization",
                                Prefix: "Bearer",
                            },
                        };
                    default:
                        return {
                            ApiKey: {
                                Name: "Authorization",
                                Prefix: schemeOrApiKeyPrefix,
                            },
                        };
                }
            }
            break;
        default:
            throw new Error(`un-supported authentication scheme ${scheme.type}`);
    }
}
function processOAuth2(scheme) {
    let scopes = undefined;
    for (const flow of scheme.flows) {
        if (flow.scopes) {
            scopes ??= new Set();
            for (const scope of flow.scopes) {
                scopes.add(scope.value);
            }
        }
    }
    return scopes
        ? {
            OAuth2: { Scopes: Array.from(scopes.values()) },
        }
        : undefined;
}
//# sourceMappingURL=service-authentication.js.map