// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

package armapimanagement

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// APIGatewayConfigConnectionClient contains the methods for the APIGatewayConfigConnection group.
// Don't use this type directly, use NewAPIGatewayConfigConnectionClient() instead.
type APIGatewayConfigConnectionClient struct {
	internal       *arm.Client
	subscriptionID string
}

// NewAPIGatewayConfigConnectionClient creates a new instance of APIGatewayConfigConnectionClient with the specified values.
//   - subscriptionID - The ID of the target subscription. The value must be an UUID.
//   - credential - used to authorize requests. Usually a credential from azidentity.
//   - options - pass nil to accept the default values.
func NewAPIGatewayConfigConnectionClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*APIGatewayConfigConnectionClient, error) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &APIGatewayConfigConnectionClient{
		subscriptionID: subscriptionID,
		internal:       cl,
	}
	return client, nil
}

// BeginCreateOrUpdate - Creates or updates an API Management gateway config connection. This is long running operation and
// could take several minutes to complete.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-05-01
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - gatewayName - The name of the API Management gateway.
//   - configConnectionName - The name of the API Management gateway config connection.
//   - parameters - Parameters supplied to the CreateOrUpdate API Management gateway config connection operation.
//   - options - APIGatewayConfigConnectionClientBeginCreateOrUpdateOptions contains the optional parameters for the APIGatewayConfigConnectionClient.BeginCreateOrUpdate
//     method.
func (client *APIGatewayConfigConnectionClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, configConnectionName string, parameters GatewayConfigConnectionResource, options *APIGatewayConfigConnectionClientBeginCreateOrUpdateOptions) (*runtime.Poller[APIGatewayConfigConnectionClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceGroupName, gatewayName, configConnectionName, parameters, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[APIGatewayConfigConnectionClientCreateOrUpdateResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[APIGatewayConfigConnectionClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Creates or updates an API Management gateway config connection. This is long running operation and could
// take several minutes to complete.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-05-01
func (client *APIGatewayConfigConnectionClient) createOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, configConnectionName string, parameters GatewayConfigConnectionResource, options *APIGatewayConfigConnectionClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "APIGatewayConfigConnectionClient.BeginCreateOrUpdate"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, gatewayName, configConnectionName, parameters, options)
	if err != nil {
		return nil, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *APIGatewayConfigConnectionClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, configConnectionName string, parameters GatewayConfigConnectionResource, _ *APIGatewayConfigConnectionClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/gateways/{gatewayName}/configConnections/{configConnectionName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if gatewayName == "" {
		return nil, errors.New("parameter gatewayName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName))
	if configConnectionName == "" {
		return nil, errors.New("parameter configConnectionName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{configConnectionName}", url.PathEscape(configConnectionName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-05-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, parameters); err != nil {
		return nil, err
	}
	return req, nil
}

// BeginDelete - Deletes an existing API Management gateway config connection.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-05-01
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - gatewayName - The name of the API Management gateway.
//   - configConnectionName - The name of the API Management gateway config connection.
//   - ifMatch - ETag of the Entity. ETag should match the current entity state from the header response of the GET request or
//     it should be * for unconditional update.
//   - options - APIGatewayConfigConnectionClientBeginDeleteOptions contains the optional parameters for the APIGatewayConfigConnectionClient.BeginDelete
//     method.
func (client *APIGatewayConfigConnectionClient) BeginDelete(ctx context.Context, resourceGroupName string, gatewayName string, configConnectionName string, ifMatch string, options *APIGatewayConfigConnectionClientBeginDeleteOptions) (*runtime.Poller[APIGatewayConfigConnectionClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, gatewayName, configConnectionName, ifMatch, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[APIGatewayConfigConnectionClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[APIGatewayConfigConnectionClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Deletes an existing API Management gateway config connection.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-05-01
func (client *APIGatewayConfigConnectionClient) deleteOperation(ctx context.Context, resourceGroupName string, gatewayName string, configConnectionName string, ifMatch string, options *APIGatewayConfigConnectionClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "APIGatewayConfigConnectionClient.BeginDelete"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.deleteCreateRequest(ctx, resourceGroupName, gatewayName, configConnectionName, ifMatch, options)
	if err != nil {
		return nil, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// deleteCreateRequest creates the Delete request.
func (client *APIGatewayConfigConnectionClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, configConnectionName string, ifMatch string, _ *APIGatewayConfigConnectionClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/gateways/{gatewayName}/configConnections/{configConnectionName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if gatewayName == "" {
		return nil, errors.New("parameter gatewayName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName))
	if configConnectionName == "" {
		return nil, errors.New("parameter configConnectionName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{configConnectionName}", url.PathEscape(configConnectionName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-05-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	req.Raw().Header["If-Match"] = []string{ifMatch}
	return req, nil
}

// Get - Gets an API Management gateway config connection resource description.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-05-01
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - gatewayName - The name of the API Management gateway.
//   - configConnectionName - The name of the API Management gateway config connection.
//   - options - APIGatewayConfigConnectionClientGetOptions contains the optional parameters for the APIGatewayConfigConnectionClient.Get
//     method.
func (client *APIGatewayConfigConnectionClient) Get(ctx context.Context, resourceGroupName string, gatewayName string, configConnectionName string, options *APIGatewayConfigConnectionClientGetOptions) (APIGatewayConfigConnectionClientGetResponse, error) {
	var err error
	const operationName = "APIGatewayConfigConnectionClient.Get"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.getCreateRequest(ctx, resourceGroupName, gatewayName, configConnectionName, options)
	if err != nil {
		return APIGatewayConfigConnectionClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return APIGatewayConfigConnectionClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return APIGatewayConfigConnectionClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *APIGatewayConfigConnectionClient) getCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, configConnectionName string, _ *APIGatewayConfigConnectionClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/gateways/{gatewayName}/configConnections/{configConnectionName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if gatewayName == "" {
		return nil, errors.New("parameter gatewayName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName))
	if configConnectionName == "" {
		return nil, errors.New("parameter configConnectionName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{configConnectionName}", url.PathEscape(configConnectionName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-05-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *APIGatewayConfigConnectionClient) getHandleResponse(resp *http.Response) (APIGatewayConfigConnectionClientGetResponse, error) {
	result := APIGatewayConfigConnectionClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.GatewayConfigConnectionResource); err != nil {
		return APIGatewayConfigConnectionClientGetResponse{}, err
	}
	return result, nil
}

// NewListByGatewayPager - List all API Management gateway config connections within a gateway.
//
// Generated from API version 2024-05-01
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - gatewayName - The name of the API Management gateway.
//   - options - APIGatewayConfigConnectionClientListByGatewayOptions contains the optional parameters for the APIGatewayConfigConnectionClient.NewListByGatewayPager
//     method.
func (client *APIGatewayConfigConnectionClient) NewListByGatewayPager(resourceGroupName string, gatewayName string, options *APIGatewayConfigConnectionClientListByGatewayOptions) *runtime.Pager[APIGatewayConfigConnectionClientListByGatewayResponse] {
	return runtime.NewPager(runtime.PagingHandler[APIGatewayConfigConnectionClientListByGatewayResponse]{
		More: func(page APIGatewayConfigConnectionClientListByGatewayResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *APIGatewayConfigConnectionClientListByGatewayResponse) (APIGatewayConfigConnectionClientListByGatewayResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "APIGatewayConfigConnectionClient.NewListByGatewayPager")
			nextLink := ""
			if page != nil {
				nextLink = *page.NextLink
			}
			resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
				return client.listByGatewayCreateRequest(ctx, resourceGroupName, gatewayName, options)
			}, nil)
			if err != nil {
				return APIGatewayConfigConnectionClientListByGatewayResponse{}, err
			}
			return client.listByGatewayHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByGatewayCreateRequest creates the ListByGateway request.
func (client *APIGatewayConfigConnectionClient) listByGatewayCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, _ *APIGatewayConfigConnectionClientListByGatewayOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/gateways/{gatewayName}/configConnections"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if gatewayName == "" {
		return nil, errors.New("parameter gatewayName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-05-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByGatewayHandleResponse handles the ListByGateway response.
func (client *APIGatewayConfigConnectionClient) listByGatewayHandleResponse(resp *http.Response) (APIGatewayConfigConnectionClientListByGatewayResponse, error) {
	result := APIGatewayConfigConnectionClientListByGatewayResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.GatewayConfigConnectionListResult); err != nil {
		return APIGatewayConfigConnectionClientListByGatewayResponse{}, err
	}
	return result, nil
}
