"use strict";
/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiManagementClient = void 0;
const tslib_1 = require("tslib");
const coreClient = tslib_1.__importStar(require("@azure/core-client"));
const coreRestPipeline = tslib_1.__importStar(require("@azure/core-rest-pipeline"));
const core_lro_1 = require("@azure/core-lro");
const lroImpl_js_1 = require("./lroImpl.js");
const index_js_1 = require("./operations/index.js");
const Parameters = tslib_1.__importStar(require("./models/parameters.js"));
const Mappers = tslib_1.__importStar(require("./models/mappers.js"));
class ApiManagementClient extends coreClient.ServiceClient {
    constructor(credentials, subscriptionIdOrOptions, options) {
        var _a, _b, _c;
        if (credentials === undefined) {
            throw new Error("'credentials' cannot be null");
        }
        let subscriptionId;
        if (typeof subscriptionIdOrOptions === "string") {
            subscriptionId = subscriptionIdOrOptions;
        }
        else if (typeof subscriptionIdOrOptions === "object") {
            options = subscriptionIdOrOptions;
        }
        // Initializing default values for options
        if (!options) {
            options = {};
        }
        const defaults = {
            requestContentType: "application/json; charset=utf-8",
            credential: credentials,
        };
        const packageDetails = `azsdk-js-arm-apimanagement/10.0.0`;
        const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix
            ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
            : `${packageDetails}`;
        const optionsWithDefaults = Object.assign(Object.assign(Object.assign({}, defaults), options), { userAgentOptions: {
                userAgentPrefix,
            }, endpoint: (_b = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri) !== null && _b !== void 0 ? _b : "https://management.azure.com" });
        super(optionsWithDefaults);
        let bearerTokenAuthenticationPolicyFound = false;
        if ((options === null || options === void 0 ? void 0 : options.pipeline) && options.pipeline.getOrderedPolicies().length > 0) {
            const pipelinePolicies = options.pipeline.getOrderedPolicies();
            bearerTokenAuthenticationPolicyFound = pipelinePolicies.some((pipelinePolicy) => pipelinePolicy.name ===
                coreRestPipeline.bearerTokenAuthenticationPolicyName);
        }
        if (!options ||
            !options.pipeline ||
            options.pipeline.getOrderedPolicies().length == 0 ||
            !bearerTokenAuthenticationPolicyFound) {
            this.pipeline.removePolicy({
                name: coreRestPipeline.bearerTokenAuthenticationPolicyName,
            });
            this.pipeline.addPolicy(coreRestPipeline.bearerTokenAuthenticationPolicy({
                credential: credentials,
                scopes: (_c = optionsWithDefaults.credentialScopes) !== null && _c !== void 0 ? _c : `${optionsWithDefaults.endpoint}/.default`,
                challengeCallbacks: {
                    authorizeRequestOnChallenge: coreClient.authorizeRequestOnClaimChallenge,
                },
            }));
        }
        // Parameter assignments
        this.subscriptionId = subscriptionId;
        // Assigning values to Constant parameters
        this.$host = options.$host || "https://management.azure.com";
        this.apiVersion = options.apiVersion || "2024-05-01";
        this.apiGateway = new index_js_1.ApiGatewayImpl(this);
        this.apiManagementGatewaySkus = new index_js_1.ApiManagementGatewaySkusImpl(this);
        this.allPolicies = new index_js_1.AllPoliciesImpl(this);
        this.api = new index_js_1.ApiImpl(this);
        this.apiRevision = new index_js_1.ApiRevisionImpl(this);
        this.apiRelease = new index_js_1.ApiReleaseImpl(this);
        this.apiOperation = new index_js_1.ApiOperationImpl(this);
        this.apiOperationPolicy = new index_js_1.ApiOperationPolicyImpl(this);
        this.tag = new index_js_1.TagImpl(this);
        this.graphQLApiResolver = new index_js_1.GraphQLApiResolverImpl(this);
        this.graphQLApiResolverPolicy = new index_js_1.GraphQLApiResolverPolicyImpl(this);
        this.apiProduct = new index_js_1.ApiProductImpl(this);
        this.apiPolicy = new index_js_1.ApiPolicyImpl(this);
        this.apiSchema = new index_js_1.ApiSchemaImpl(this);
        this.apiDiagnostic = new index_js_1.ApiDiagnosticImpl(this);
        this.apiIssue = new index_js_1.ApiIssueImpl(this);
        this.apiIssueComment = new index_js_1.ApiIssueCommentImpl(this);
        this.apiIssueAttachment = new index_js_1.ApiIssueAttachmentImpl(this);
        this.apiTagDescription = new index_js_1.ApiTagDescriptionImpl(this);
        this.operationOperations = new index_js_1.OperationOperationsImpl(this);
        this.apiWiki = new index_js_1.ApiWikiImpl(this);
        this.apiWikis = new index_js_1.ApiWikisImpl(this);
        this.apiExport = new index_js_1.ApiExportImpl(this);
        this.apiVersionSet = new index_js_1.ApiVersionSetImpl(this);
        this.authorizationProvider = new index_js_1.AuthorizationProviderImpl(this);
        this.authorization = new index_js_1.AuthorizationImpl(this);
        this.authorizationLoginLinks = new index_js_1.AuthorizationLoginLinksImpl(this);
        this.authorizationAccessPolicy = new index_js_1.AuthorizationAccessPolicyImpl(this);
        this.authorizationServer = new index_js_1.AuthorizationServerImpl(this);
        this.backend = new index_js_1.BackendImpl(this);
        this.cache = new index_js_1.CacheImpl(this);
        this.certificate = new index_js_1.CertificateImpl(this);
        this.contentType = new index_js_1.ContentTypeImpl(this);
        this.contentItem = new index_js_1.ContentItemImpl(this);
        this.deletedServices = new index_js_1.DeletedServicesImpl(this);
        this.apiManagementOperations = new index_js_1.ApiManagementOperationsImpl(this);
        this.apiManagementServiceSkus = new index_js_1.ApiManagementServiceSkusImpl(this);
        this.apiManagementService = new index_js_1.ApiManagementServiceImpl(this);
        this.diagnostic = new index_js_1.DiagnosticImpl(this);
        this.documentation = new index_js_1.DocumentationImpl(this);
        this.emailTemplate = new index_js_1.EmailTemplateImpl(this);
        this.apiGatewayConfigConnection = new index_js_1.ApiGatewayConfigConnectionImpl(this);
        this.gateway = new index_js_1.GatewayImpl(this);
        this.gatewayHostnameConfiguration = new index_js_1.GatewayHostnameConfigurationImpl(this);
        this.gatewayApi = new index_js_1.GatewayApiImpl(this);
        this.gatewayCertificateAuthority = new index_js_1.GatewayCertificateAuthorityImpl(this);
        this.group = new index_js_1.GroupImpl(this);
        this.groupUser = new index_js_1.GroupUserImpl(this);
        this.identityProvider = new index_js_1.IdentityProviderImpl(this);
        this.issue = new index_js_1.IssueImpl(this);
        this.logger = new index_js_1.LoggerImpl(this);
        this.namedValue = new index_js_1.NamedValueImpl(this);
        this.networkStatus = new index_js_1.NetworkStatusImpl(this);
        this.notification = new index_js_1.NotificationImpl(this);
        this.notificationRecipientUser = new index_js_1.NotificationRecipientUserImpl(this);
        this.notificationRecipientEmail = new index_js_1.NotificationRecipientEmailImpl(this);
        this.openIdConnectProvider = new index_js_1.OpenIdConnectProviderImpl(this);
        this.outboundNetworkDependenciesEndpoints =
            new index_js_1.OutboundNetworkDependenciesEndpointsImpl(this);
        this.policy = new index_js_1.PolicyImpl(this);
        this.policyDescription = new index_js_1.PolicyDescriptionImpl(this);
        this.policyFragment = new index_js_1.PolicyFragmentImpl(this);
        this.policyRestriction = new index_js_1.PolicyRestrictionImpl(this);
        this.policyRestrictionValidations = new index_js_1.PolicyRestrictionValidationsImpl(this);
        this.portalConfig = new index_js_1.PortalConfigImpl(this);
        this.portalRevision = new index_js_1.PortalRevisionImpl(this);
        this.portalSettings = new index_js_1.PortalSettingsImpl(this);
        this.signInSettings = new index_js_1.SignInSettingsImpl(this);
        this.signUpSettings = new index_js_1.SignUpSettingsImpl(this);
        this.delegationSettings = new index_js_1.DelegationSettingsImpl(this);
        this.privateEndpointConnectionOperations =
            new index_js_1.PrivateEndpointConnectionOperationsImpl(this);
        this.product = new index_js_1.ProductImpl(this);
        this.productApi = new index_js_1.ProductApiImpl(this);
        this.productGroup = new index_js_1.ProductGroupImpl(this);
        this.productSubscriptions = new index_js_1.ProductSubscriptionsImpl(this);
        this.productPolicy = new index_js_1.ProductPolicyImpl(this);
        this.productWiki = new index_js_1.ProductWikiImpl(this);
        this.productWikis = new index_js_1.ProductWikisImpl(this);
        this.productApiLink = new index_js_1.ProductApiLinkImpl(this);
        this.productGroupLink = new index_js_1.ProductGroupLinkImpl(this);
        this.quotaByCounterKeys = new index_js_1.QuotaByCounterKeysImpl(this);
        this.quotaByPeriodKeys = new index_js_1.QuotaByPeriodKeysImpl(this);
        this.region = new index_js_1.RegionImpl(this);
        this.reports = new index_js_1.ReportsImpl(this);
        this.globalSchema = new index_js_1.GlobalSchemaImpl(this);
        this.tenantSettings = new index_js_1.TenantSettingsImpl(this);
        this.apiManagementSkus = new index_js_1.ApiManagementSkusImpl(this);
        this.subscription = new index_js_1.SubscriptionImpl(this);
        this.tagResource = new index_js_1.TagResourceImpl(this);
        this.tagApiLink = new index_js_1.TagApiLinkImpl(this);
        this.tagOperationLink = new index_js_1.TagOperationLinkImpl(this);
        this.tagProductLink = new index_js_1.TagProductLinkImpl(this);
        this.tenantAccess = new index_js_1.TenantAccessImpl(this);
        this.tenantAccessGit = new index_js_1.TenantAccessGitImpl(this);
        this.tenantConfiguration = new index_js_1.TenantConfigurationImpl(this);
        this.user = new index_js_1.UserImpl(this);
        this.userGroup = new index_js_1.UserGroupImpl(this);
        this.userSubscription = new index_js_1.UserSubscriptionImpl(this);
        this.userIdentities = new index_js_1.UserIdentitiesImpl(this);
        this.userConfirmationPassword = new index_js_1.UserConfirmationPasswordImpl(this);
        this.workspaceBackend = new index_js_1.WorkspaceBackendImpl(this);
        this.workspaceCertificate = new index_js_1.WorkspaceCertificateImpl(this);
        this.workspaceDiagnostic = new index_js_1.WorkspaceDiagnosticImpl(this);
        this.workspaceApiDiagnostic = new index_js_1.WorkspaceApiDiagnosticImpl(this);
        this.apiManagementWorkspaceLinks = new index_js_1.ApiManagementWorkspaceLinksImpl(this);
        this.apiManagementWorkspaceLink = new index_js_1.ApiManagementWorkspaceLinkImpl(this);
        this.workspaceLogger = new index_js_1.WorkspaceLoggerImpl(this);
        this.workspace = new index_js_1.WorkspaceImpl(this);
        this.workspacePolicy = new index_js_1.WorkspacePolicyImpl(this);
        this.workspaceNamedValue = new index_js_1.WorkspaceNamedValueImpl(this);
        this.workspaceGlobalSchema = new index_js_1.WorkspaceGlobalSchemaImpl(this);
        this.workspaceNotification = new index_js_1.WorkspaceNotificationImpl(this);
        this.workspaceNotificationRecipientUser =
            new index_js_1.WorkspaceNotificationRecipientUserImpl(this);
        this.workspaceNotificationRecipientEmail =
            new index_js_1.WorkspaceNotificationRecipientEmailImpl(this);
        this.workspacePolicyFragment = new index_js_1.WorkspacePolicyFragmentImpl(this);
        this.workspaceGroup = new index_js_1.WorkspaceGroupImpl(this);
        this.workspaceGroupUser = new index_js_1.WorkspaceGroupUserImpl(this);
        this.workspaceSubscription = new index_js_1.WorkspaceSubscriptionImpl(this);
        this.workspaceApiVersionSet = new index_js_1.WorkspaceApiVersionSetImpl(this);
        this.workspaceApi = new index_js_1.WorkspaceApiImpl(this);
        this.workspaceApiRevision = new index_js_1.WorkspaceApiRevisionImpl(this);
        this.workspaceApiRelease = new index_js_1.WorkspaceApiReleaseImpl(this);
        this.workspaceApiOperation = new index_js_1.WorkspaceApiOperationImpl(this);
        this.workspaceApiOperationPolicy = new index_js_1.WorkspaceApiOperationPolicyImpl(this);
        this.workspaceApiPolicy = new index_js_1.WorkspaceApiPolicyImpl(this);
        this.workspaceApiSchema = new index_js_1.WorkspaceApiSchemaImpl(this);
        this.workspaceProduct = new index_js_1.WorkspaceProductImpl(this);
        this.workspaceProductApiLink = new index_js_1.WorkspaceProductApiLinkImpl(this);
        this.workspaceProductGroupLink = new index_js_1.WorkspaceProductGroupLinkImpl(this);
        this.workspaceProductPolicy = new index_js_1.WorkspaceProductPolicyImpl(this);
        this.workspaceTag = new index_js_1.WorkspaceTagImpl(this);
        this.workspaceTagApiLink = new index_js_1.WorkspaceTagApiLinkImpl(this);
        this.workspaceTagOperationLink = new index_js_1.WorkspaceTagOperationLinkImpl(this);
        this.workspaceTagProductLink = new index_js_1.WorkspaceTagProductLinkImpl(this);
        this.workspaceApiExport = new index_js_1.WorkspaceApiExportImpl(this);
        this.operationStatus = new index_js_1.OperationStatusImpl(this);
        this.operationsResults = new index_js_1.OperationsResultsImpl(this);
        this.addCustomApiVersionPolicy(options.apiVersion);
    }
    /** A function that adds a policy that sets the api-version (or equivalent) to reflect the library version. */
    addCustomApiVersionPolicy(apiVersion) {
        if (!apiVersion) {
            return;
        }
        const apiVersionPolicy = {
            name: "CustomApiVersionPolicy",
            async sendRequest(request, next) {
                const param = request.url.split("?");
                if (param.length > 1) {
                    const newParams = param[1].split("&").map((item) => {
                        if (item.indexOf("api-version") > -1) {
                            return "api-version=" + apiVersion;
                        }
                        else {
                            return item;
                        }
                    });
                    request.url = param[0] + "?" + newParams.join("&");
                }
                return next(request);
            },
        };
        this.pipeline.addPolicy(apiVersionPolicy);
    }
    /**
     * Performs a connectivity check between the API Management service and a given destination, and
     * returns metrics for the connection, as well as errors encountered while trying to establish it.
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param serviceName The name of the API Management service.
     * @param connectivityCheckRequestParams Connectivity Check request parameters.
     * @param options The options parameters.
     */
    async beginPerformConnectivityCheckAsync(resourceGroupName, serviceName, connectivityCheckRequestParams, options) {
        const directSendOperation = async (args, spec) => {
            return this.sendOperationRequest(args, spec);
        };
        const sendOperationFn = async (args, spec) => {
            var _a;
            let currentRawResponse = undefined;
            const providedCallback = (_a = args.options) === null || _a === void 0 ? void 0 : _a.onResponse;
            const callback = (rawResponse, flatResponse) => {
                currentRawResponse = rawResponse;
                providedCallback === null || providedCallback === void 0 ? void 0 : providedCallback(rawResponse, flatResponse);
            };
            const updatedArgs = Object.assign(Object.assign({}, args), { options: Object.assign(Object.assign({}, args.options), { onResponse: callback }) });
            const flatResponse = await directSendOperation(updatedArgs, spec);
            return {
                flatResponse,
                rawResponse: {
                    statusCode: currentRawResponse.status,
                    body: currentRawResponse.parsedBody,
                    headers: currentRawResponse.headers.toJSON(),
                },
            };
        };
        const lro = (0, lroImpl_js_1.createLroSpec)({
            sendOperationFn,
            args: {
                resourceGroupName,
                serviceName,
                connectivityCheckRequestParams,
                options,
            },
            spec: performConnectivityCheckAsyncOperationSpec,
        });
        const poller = await (0, core_lro_1.createHttpPoller)(lro, {
            restoreFrom: options === null || options === void 0 ? void 0 : options.resumeFrom,
            intervalInMs: options === null || options === void 0 ? void 0 : options.updateIntervalInMs,
            resourceLocationConfig: "location",
        });
        await poller.poll();
        return poller;
    }
    /**
     * Performs a connectivity check between the API Management service and a given destination, and
     * returns metrics for the connection, as well as errors encountered while trying to establish it.
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param serviceName The name of the API Management service.
     * @param connectivityCheckRequestParams Connectivity Check request parameters.
     * @param options The options parameters.
     */
    async beginPerformConnectivityCheckAsyncAndWait(resourceGroupName, serviceName, connectivityCheckRequestParams, options) {
        const poller = await this.beginPerformConnectivityCheckAsync(resourceGroupName, serviceName, connectivityCheckRequestParams, options);
        return poller.pollUntilDone();
    }
}
exports.ApiManagementClient = ApiManagementClient;
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const performConnectivityCheckAsyncOperationSpec = {
    path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/connectivityCheck",
    httpMethod: "POST",
    responses: {
        200: {
            bodyMapper: Mappers.ConnectivityCheckResponse,
        },
        201: {
            bodyMapper: Mappers.ConnectivityCheckResponse,
        },
        202: {
            bodyMapper: Mappers.ConnectivityCheckResponse,
        },
        204: {
            bodyMapper: Mappers.ConnectivityCheckResponse,
        },
        default: {
            bodyMapper: Mappers.ErrorResponse,
        },
    },
    requestBody: Parameters.connectivityCheckRequestParams,
    queryParameters: [Parameters.apiVersion],
    urlParameters: [
        Parameters.$host,
        Parameters.resourceGroupName,
        Parameters.subscriptionId,
        Parameters.serviceName,
    ],
    headerParameters: [Parameters.contentType, Parameters.accept],
    mediaType: "json",
    serializer,
};
//# sourceMappingURL=apiManagementClient.js.map