/*
 * 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.
 */
import * as coreClient from "@azure/core-client";
import * as coreRestPipeline from "@azure/core-rest-pipeline";
import { createHttpPoller, } from "@azure/core-lro";
import { createLroSpec } from "./lroImpl.js";
import { ApiGatewayImpl, ApiManagementGatewaySkusImpl, AllPoliciesImpl, ApiImpl, ApiRevisionImpl, ApiReleaseImpl, ApiOperationImpl, ApiOperationPolicyImpl, TagImpl, GraphQLApiResolverImpl, GraphQLApiResolverPolicyImpl, ApiProductImpl, ApiPolicyImpl, ApiSchemaImpl, ApiDiagnosticImpl, ApiIssueImpl, ApiIssueCommentImpl, ApiIssueAttachmentImpl, ApiTagDescriptionImpl, OperationOperationsImpl, ApiWikiImpl, ApiWikisImpl, ApiExportImpl, ApiVersionSetImpl, AuthorizationProviderImpl, AuthorizationImpl, AuthorizationLoginLinksImpl, AuthorizationAccessPolicyImpl, AuthorizationServerImpl, BackendImpl, CacheImpl, CertificateImpl, ContentTypeImpl, ContentItemImpl, DeletedServicesImpl, ApiManagementOperationsImpl, ApiManagementServiceSkusImpl, ApiManagementServiceImpl, DiagnosticImpl, DocumentationImpl, EmailTemplateImpl, ApiGatewayConfigConnectionImpl, GatewayImpl, GatewayHostnameConfigurationImpl, GatewayApiImpl, GatewayCertificateAuthorityImpl, GroupImpl, GroupUserImpl, IdentityProviderImpl, IssueImpl, LoggerImpl, NamedValueImpl, NetworkStatusImpl, NotificationImpl, NotificationRecipientUserImpl, NotificationRecipientEmailImpl, OpenIdConnectProviderImpl, OutboundNetworkDependenciesEndpointsImpl, PolicyImpl, PolicyDescriptionImpl, PolicyFragmentImpl, PolicyRestrictionImpl, PolicyRestrictionValidationsImpl, PortalConfigImpl, PortalRevisionImpl, PortalSettingsImpl, SignInSettingsImpl, SignUpSettingsImpl, DelegationSettingsImpl, PrivateEndpointConnectionOperationsImpl, ProductImpl, ProductApiImpl, ProductGroupImpl, ProductSubscriptionsImpl, ProductPolicyImpl, ProductWikiImpl, ProductWikisImpl, ProductApiLinkImpl, ProductGroupLinkImpl, QuotaByCounterKeysImpl, QuotaByPeriodKeysImpl, RegionImpl, ReportsImpl, GlobalSchemaImpl, TenantSettingsImpl, ApiManagementSkusImpl, SubscriptionImpl, TagResourceImpl, TagApiLinkImpl, TagOperationLinkImpl, TagProductLinkImpl, TenantAccessImpl, TenantAccessGitImpl, TenantConfigurationImpl, UserImpl, UserGroupImpl, UserSubscriptionImpl, UserIdentitiesImpl, UserConfirmationPasswordImpl, WorkspaceBackendImpl, WorkspaceCertificateImpl, WorkspaceDiagnosticImpl, WorkspaceApiDiagnosticImpl, ApiManagementWorkspaceLinksImpl, ApiManagementWorkspaceLinkImpl, WorkspaceLoggerImpl, WorkspaceImpl, WorkspacePolicyImpl, WorkspaceNamedValueImpl, WorkspaceGlobalSchemaImpl, WorkspaceNotificationImpl, WorkspaceNotificationRecipientUserImpl, WorkspaceNotificationRecipientEmailImpl, WorkspacePolicyFragmentImpl, WorkspaceGroupImpl, WorkspaceGroupUserImpl, WorkspaceSubscriptionImpl, WorkspaceApiVersionSetImpl, WorkspaceApiImpl, WorkspaceApiRevisionImpl, WorkspaceApiReleaseImpl, WorkspaceApiOperationImpl, WorkspaceApiOperationPolicyImpl, WorkspaceApiPolicyImpl, WorkspaceApiSchemaImpl, WorkspaceProductImpl, WorkspaceProductApiLinkImpl, WorkspaceProductGroupLinkImpl, WorkspaceProductPolicyImpl, WorkspaceTagImpl, WorkspaceTagApiLinkImpl, WorkspaceTagOperationLinkImpl, WorkspaceTagProductLinkImpl, WorkspaceApiExportImpl, OperationStatusImpl, OperationsResultsImpl, } from "./operations/index.js";
import * as Parameters from "./models/parameters.js";
import * as Mappers from "./models/mappers.js";
export 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 ApiGatewayImpl(this);
        this.apiManagementGatewaySkus = new ApiManagementGatewaySkusImpl(this);
        this.allPolicies = new AllPoliciesImpl(this);
        this.api = new ApiImpl(this);
        this.apiRevision = new ApiRevisionImpl(this);
        this.apiRelease = new ApiReleaseImpl(this);
        this.apiOperation = new ApiOperationImpl(this);
        this.apiOperationPolicy = new ApiOperationPolicyImpl(this);
        this.tag = new TagImpl(this);
        this.graphQLApiResolver = new GraphQLApiResolverImpl(this);
        this.graphQLApiResolverPolicy = new GraphQLApiResolverPolicyImpl(this);
        this.apiProduct = new ApiProductImpl(this);
        this.apiPolicy = new ApiPolicyImpl(this);
        this.apiSchema = new ApiSchemaImpl(this);
        this.apiDiagnostic = new ApiDiagnosticImpl(this);
        this.apiIssue = new ApiIssueImpl(this);
        this.apiIssueComment = new ApiIssueCommentImpl(this);
        this.apiIssueAttachment = new ApiIssueAttachmentImpl(this);
        this.apiTagDescription = new ApiTagDescriptionImpl(this);
        this.operationOperations = new OperationOperationsImpl(this);
        this.apiWiki = new ApiWikiImpl(this);
        this.apiWikis = new ApiWikisImpl(this);
        this.apiExport = new ApiExportImpl(this);
        this.apiVersionSet = new ApiVersionSetImpl(this);
        this.authorizationProvider = new AuthorizationProviderImpl(this);
        this.authorization = new AuthorizationImpl(this);
        this.authorizationLoginLinks = new AuthorizationLoginLinksImpl(this);
        this.authorizationAccessPolicy = new AuthorizationAccessPolicyImpl(this);
        this.authorizationServer = new AuthorizationServerImpl(this);
        this.backend = new BackendImpl(this);
        this.cache = new CacheImpl(this);
        this.certificate = new CertificateImpl(this);
        this.contentType = new ContentTypeImpl(this);
        this.contentItem = new ContentItemImpl(this);
        this.deletedServices = new DeletedServicesImpl(this);
        this.apiManagementOperations = new ApiManagementOperationsImpl(this);
        this.apiManagementServiceSkus = new ApiManagementServiceSkusImpl(this);
        this.apiManagementService = new ApiManagementServiceImpl(this);
        this.diagnostic = new DiagnosticImpl(this);
        this.documentation = new DocumentationImpl(this);
        this.emailTemplate = new EmailTemplateImpl(this);
        this.apiGatewayConfigConnection = new ApiGatewayConfigConnectionImpl(this);
        this.gateway = new GatewayImpl(this);
        this.gatewayHostnameConfiguration = new GatewayHostnameConfigurationImpl(this);
        this.gatewayApi = new GatewayApiImpl(this);
        this.gatewayCertificateAuthority = new GatewayCertificateAuthorityImpl(this);
        this.group = new GroupImpl(this);
        this.groupUser = new GroupUserImpl(this);
        this.identityProvider = new IdentityProviderImpl(this);
        this.issue = new IssueImpl(this);
        this.logger = new LoggerImpl(this);
        this.namedValue = new NamedValueImpl(this);
        this.networkStatus = new NetworkStatusImpl(this);
        this.notification = new NotificationImpl(this);
        this.notificationRecipientUser = new NotificationRecipientUserImpl(this);
        this.notificationRecipientEmail = new NotificationRecipientEmailImpl(this);
        this.openIdConnectProvider = new OpenIdConnectProviderImpl(this);
        this.outboundNetworkDependenciesEndpoints =
            new OutboundNetworkDependenciesEndpointsImpl(this);
        this.policy = new PolicyImpl(this);
        this.policyDescription = new PolicyDescriptionImpl(this);
        this.policyFragment = new PolicyFragmentImpl(this);
        this.policyRestriction = new PolicyRestrictionImpl(this);
        this.policyRestrictionValidations = new PolicyRestrictionValidationsImpl(this);
        this.portalConfig = new PortalConfigImpl(this);
        this.portalRevision = new PortalRevisionImpl(this);
        this.portalSettings = new PortalSettingsImpl(this);
        this.signInSettings = new SignInSettingsImpl(this);
        this.signUpSettings = new SignUpSettingsImpl(this);
        this.delegationSettings = new DelegationSettingsImpl(this);
        this.privateEndpointConnectionOperations =
            new PrivateEndpointConnectionOperationsImpl(this);
        this.product = new ProductImpl(this);
        this.productApi = new ProductApiImpl(this);
        this.productGroup = new ProductGroupImpl(this);
        this.productSubscriptions = new ProductSubscriptionsImpl(this);
        this.productPolicy = new ProductPolicyImpl(this);
        this.productWiki = new ProductWikiImpl(this);
        this.productWikis = new ProductWikisImpl(this);
        this.productApiLink = new ProductApiLinkImpl(this);
        this.productGroupLink = new ProductGroupLinkImpl(this);
        this.quotaByCounterKeys = new QuotaByCounterKeysImpl(this);
        this.quotaByPeriodKeys = new QuotaByPeriodKeysImpl(this);
        this.region = new RegionImpl(this);
        this.reports = new ReportsImpl(this);
        this.globalSchema = new GlobalSchemaImpl(this);
        this.tenantSettings = new TenantSettingsImpl(this);
        this.apiManagementSkus = new ApiManagementSkusImpl(this);
        this.subscription = new SubscriptionImpl(this);
        this.tagResource = new TagResourceImpl(this);
        this.tagApiLink = new TagApiLinkImpl(this);
        this.tagOperationLink = new TagOperationLinkImpl(this);
        this.tagProductLink = new TagProductLinkImpl(this);
        this.tenantAccess = new TenantAccessImpl(this);
        this.tenantAccessGit = new TenantAccessGitImpl(this);
        this.tenantConfiguration = new TenantConfigurationImpl(this);
        this.user = new UserImpl(this);
        this.userGroup = new UserGroupImpl(this);
        this.userSubscription = new UserSubscriptionImpl(this);
        this.userIdentities = new UserIdentitiesImpl(this);
        this.userConfirmationPassword = new UserConfirmationPasswordImpl(this);
        this.workspaceBackend = new WorkspaceBackendImpl(this);
        this.workspaceCertificate = new WorkspaceCertificateImpl(this);
        this.workspaceDiagnostic = new WorkspaceDiagnosticImpl(this);
        this.workspaceApiDiagnostic = new WorkspaceApiDiagnosticImpl(this);
        this.apiManagementWorkspaceLinks = new ApiManagementWorkspaceLinksImpl(this);
        this.apiManagementWorkspaceLink = new ApiManagementWorkspaceLinkImpl(this);
        this.workspaceLogger = new WorkspaceLoggerImpl(this);
        this.workspace = new WorkspaceImpl(this);
        this.workspacePolicy = new WorkspacePolicyImpl(this);
        this.workspaceNamedValue = new WorkspaceNamedValueImpl(this);
        this.workspaceGlobalSchema = new WorkspaceGlobalSchemaImpl(this);
        this.workspaceNotification = new WorkspaceNotificationImpl(this);
        this.workspaceNotificationRecipientUser =
            new WorkspaceNotificationRecipientUserImpl(this);
        this.workspaceNotificationRecipientEmail =
            new WorkspaceNotificationRecipientEmailImpl(this);
        this.workspacePolicyFragment = new WorkspacePolicyFragmentImpl(this);
        this.workspaceGroup = new WorkspaceGroupImpl(this);
        this.workspaceGroupUser = new WorkspaceGroupUserImpl(this);
        this.workspaceSubscription = new WorkspaceSubscriptionImpl(this);
        this.workspaceApiVersionSet = new WorkspaceApiVersionSetImpl(this);
        this.workspaceApi = new WorkspaceApiImpl(this);
        this.workspaceApiRevision = new WorkspaceApiRevisionImpl(this);
        this.workspaceApiRelease = new WorkspaceApiReleaseImpl(this);
        this.workspaceApiOperation = new WorkspaceApiOperationImpl(this);
        this.workspaceApiOperationPolicy = new WorkspaceApiOperationPolicyImpl(this);
        this.workspaceApiPolicy = new WorkspaceApiPolicyImpl(this);
        this.workspaceApiSchema = new WorkspaceApiSchemaImpl(this);
        this.workspaceProduct = new WorkspaceProductImpl(this);
        this.workspaceProductApiLink = new WorkspaceProductApiLinkImpl(this);
        this.workspaceProductGroupLink = new WorkspaceProductGroupLinkImpl(this);
        this.workspaceProductPolicy = new WorkspaceProductPolicyImpl(this);
        this.workspaceTag = new WorkspaceTagImpl(this);
        this.workspaceTagApiLink = new WorkspaceTagApiLinkImpl(this);
        this.workspaceTagOperationLink = new WorkspaceTagOperationLinkImpl(this);
        this.workspaceTagProductLink = new WorkspaceTagProductLinkImpl(this);
        this.workspaceApiExport = new WorkspaceApiExportImpl(this);
        this.operationStatus = new OperationStatusImpl(this);
        this.operationsResults = new 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 = createLroSpec({
            sendOperationFn,
            args: {
                resourceGroupName,
                serviceName,
                connectivityCheckRequestParams,
                options,
            },
            spec: performConnectivityCheckAsyncOperationSpec,
        });
        const poller = await 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();
    }
}
// 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