// 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 fake

import (
	"context"
	"errors"
	"fmt"
	azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/apimanagement/armapimanagement/v3"
	"net/http"
	"net/url"
	"regexp"
)

// APIGatewayConfigConnectionServer is a fake server for instances of the armapimanagement.APIGatewayConfigConnectionClient type.
type APIGatewayConfigConnectionServer struct {
	// BeginCreateOrUpdate is the fake for method APIGatewayConfigConnectionClient.BeginCreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, gatewayName string, configConnectionName string, parameters armapimanagement.GatewayConfigConnectionResource, options *armapimanagement.APIGatewayConfigConnectionClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armapimanagement.APIGatewayConfigConnectionClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method APIGatewayConfigConnectionClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, gatewayName string, configConnectionName string, ifMatch string, options *armapimanagement.APIGatewayConfigConnectionClientBeginDeleteOptions) (resp azfake.PollerResponder[armapimanagement.APIGatewayConfigConnectionClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method APIGatewayConfigConnectionClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, gatewayName string, configConnectionName string, options *armapimanagement.APIGatewayConfigConnectionClientGetOptions) (resp azfake.Responder[armapimanagement.APIGatewayConfigConnectionClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByGatewayPager is the fake for method APIGatewayConfigConnectionClient.NewListByGatewayPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByGatewayPager func(resourceGroupName string, gatewayName string, options *armapimanagement.APIGatewayConfigConnectionClientListByGatewayOptions) (resp azfake.PagerResponder[armapimanagement.APIGatewayConfigConnectionClientListByGatewayResponse])
}

// NewAPIGatewayConfigConnectionServerTransport creates a new instance of APIGatewayConfigConnectionServerTransport with the provided implementation.
// The returned APIGatewayConfigConnectionServerTransport instance is connected to an instance of armapimanagement.APIGatewayConfigConnectionClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewAPIGatewayConfigConnectionServerTransport(srv *APIGatewayConfigConnectionServer) *APIGatewayConfigConnectionServerTransport {
	return &APIGatewayConfigConnectionServerTransport{
		srv:                   srv,
		beginCreateOrUpdate:   newTracker[azfake.PollerResponder[armapimanagement.APIGatewayConfigConnectionClientCreateOrUpdateResponse]](),
		beginDelete:           newTracker[azfake.PollerResponder[armapimanagement.APIGatewayConfigConnectionClientDeleteResponse]](),
		newListByGatewayPager: newTracker[azfake.PagerResponder[armapimanagement.APIGatewayConfigConnectionClientListByGatewayResponse]](),
	}
}

// APIGatewayConfigConnectionServerTransport connects instances of armapimanagement.APIGatewayConfigConnectionClient to instances of APIGatewayConfigConnectionServer.
// Don't use this type directly, use NewAPIGatewayConfigConnectionServerTransport instead.
type APIGatewayConfigConnectionServerTransport struct {
	srv                   *APIGatewayConfigConnectionServer
	beginCreateOrUpdate   *tracker[azfake.PollerResponder[armapimanagement.APIGatewayConfigConnectionClientCreateOrUpdateResponse]]
	beginDelete           *tracker[azfake.PollerResponder[armapimanagement.APIGatewayConfigConnectionClientDeleteResponse]]
	newListByGatewayPager *tracker[azfake.PagerResponder[armapimanagement.APIGatewayConfigConnectionClientListByGatewayResponse]]
}

// Do implements the policy.Transporter interface for APIGatewayConfigConnectionServerTransport.
func (a *APIGatewayConfigConnectionServerTransport) Do(req *http.Request) (*http.Response, error) {
	rawMethod := req.Context().Value(runtime.CtxAPINameKey{})
	method, ok := rawMethod.(string)
	if !ok {
		return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")}
	}

	return a.dispatchToMethodFake(req, method)
}

func (a *APIGatewayConfigConnectionServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result)
	defer close(resultChan)

	go func() {
		var intercepted bool
		var res result
		if apiGatewayConfigConnectionServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = apiGatewayConfigConnectionServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "APIGatewayConfigConnectionClient.BeginCreateOrUpdate":
				res.resp, res.err = a.dispatchBeginCreateOrUpdate(req)
			case "APIGatewayConfigConnectionClient.BeginDelete":
				res.resp, res.err = a.dispatchBeginDelete(req)
			case "APIGatewayConfigConnectionClient.Get":
				res.resp, res.err = a.dispatchGet(req)
			case "APIGatewayConfigConnectionClient.NewListByGatewayPager":
				res.resp, res.err = a.dispatchNewListByGatewayPager(req)
			default:
				res.err = fmt.Errorf("unhandled API %s", method)
			}

		}
		select {
		case resultChan <- res:
		case <-req.Context().Done():
		}
	}()

	select {
	case <-req.Context().Done():
		return nil, req.Context().Err()
	case res := <-resultChan:
		return res.resp, res.err
	}
}

func (a *APIGatewayConfigConnectionServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if a.srv.BeginCreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")}
	}
	beginCreateOrUpdate := a.beginCreateOrUpdate.get(req)
	if beginCreateOrUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiManagement/gateways/(?P<gatewayName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/configConnections/(?P<configConnectionName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 4 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		body, err := server.UnmarshalRequestAsJSON[armapimanagement.GatewayConfigConnectionResource](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		gatewayNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("gatewayName")])
		if err != nil {
			return nil, err
		}
		configConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("configConnectionName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := a.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, gatewayNameParam, configConnectionNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateOrUpdate = &respr
		a.beginCreateOrUpdate.add(req, beginCreateOrUpdate)
	}

	resp, err := server.PollerResponderNext(beginCreateOrUpdate, req)
	if err != nil {
		return nil, err
	}

	if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) {
		a.beginCreateOrUpdate.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)}
	}
	if !server.PollerResponderMore(beginCreateOrUpdate) {
		a.beginCreateOrUpdate.remove(req)
	}

	return resp, nil
}

func (a *APIGatewayConfigConnectionServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if a.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := a.beginDelete.get(req)
	if beginDelete == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiManagement/gateways/(?P<gatewayName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/configConnections/(?P<configConnectionName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 4 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		gatewayNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("gatewayName")])
		if err != nil {
			return nil, err
		}
		configConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("configConnectionName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := a.srv.BeginDelete(req.Context(), resourceGroupNameParam, gatewayNameParam, configConnectionNameParam, getHeaderValue(req.Header, "If-Match"), nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		a.beginDelete.add(req, beginDelete)
	}

	resp, err := server.PollerResponderNext(beginDelete, req)
	if err != nil {
		return nil, err
	}

	if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) {
		a.beginDelete.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)}
	}
	if !server.PollerResponderMore(beginDelete) {
		a.beginDelete.remove(req)
	}

	return resp, nil
}

func (a *APIGatewayConfigConnectionServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if a.srv.Get == nil {
		return nil, &nonRetriableError{errors.New("fake for method Get not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiManagement/gateways/(?P<gatewayName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/configConnections/(?P<configConnectionName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 4 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	gatewayNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("gatewayName")])
	if err != nil {
		return nil, err
	}
	configConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("configConnectionName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, gatewayNameParam, configConnectionNameParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).GatewayConfigConnectionResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *APIGatewayConfigConnectionServerTransport) dispatchNewListByGatewayPager(req *http.Request) (*http.Response, error) {
	if a.srv.NewListByGatewayPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByGatewayPager not implemented")}
	}
	newListByGatewayPager := a.newListByGatewayPager.get(req)
	if newListByGatewayPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiManagement/gateways/(?P<gatewayName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/configConnections`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 3 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		gatewayNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("gatewayName")])
		if err != nil {
			return nil, err
		}
		resp := a.srv.NewListByGatewayPager(resourceGroupNameParam, gatewayNameParam, nil)
		newListByGatewayPager = &resp
		a.newListByGatewayPager.add(req, newListByGatewayPager)
		server.PagerResponderInjectNextLinks(newListByGatewayPager, req, func(page *armapimanagement.APIGatewayConfigConnectionClientListByGatewayResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByGatewayPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		a.newListByGatewayPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByGatewayPager) {
		a.newListByGatewayPager.remove(req)
	}
	return resp, nil
}

// set this to conditionally intercept incoming requests to APIGatewayConfigConnectionServerTransport
var apiGatewayConfigConnectionServerTransportInterceptor interface {
	// Do returns true if the server transport should use the returned response/error
	Do(*http.Request) (*http.Response, error, bool)
}
