// 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"
	"strconv"
)

// AuthorizationAccessPolicyServer is a fake server for instances of the armapimanagement.AuthorizationAccessPolicyClient type.
type AuthorizationAccessPolicyServer struct {
	// CreateOrUpdate is the fake for method AuthorizationAccessPolicyClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrUpdate func(ctx context.Context, resourceGroupName string, serviceName string, authorizationProviderID string, authorizationID string, authorizationAccessPolicyID string, parameters armapimanagement.AuthorizationAccessPolicyContract, options *armapimanagement.AuthorizationAccessPolicyClientCreateOrUpdateOptions) (resp azfake.Responder[armapimanagement.AuthorizationAccessPolicyClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method AuthorizationAccessPolicyClient.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, resourceGroupName string, serviceName string, authorizationProviderID string, authorizationID string, authorizationAccessPolicyID string, ifMatch string, options *armapimanagement.AuthorizationAccessPolicyClientDeleteOptions) (resp azfake.Responder[armapimanagement.AuthorizationAccessPolicyClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method AuthorizationAccessPolicyClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, serviceName string, authorizationProviderID string, authorizationID string, authorizationAccessPolicyID string, options *armapimanagement.AuthorizationAccessPolicyClientGetOptions) (resp azfake.Responder[armapimanagement.AuthorizationAccessPolicyClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByAuthorizationPager is the fake for method AuthorizationAccessPolicyClient.NewListByAuthorizationPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByAuthorizationPager func(resourceGroupName string, serviceName string, authorizationProviderID string, authorizationID string, options *armapimanagement.AuthorizationAccessPolicyClientListByAuthorizationOptions) (resp azfake.PagerResponder[armapimanagement.AuthorizationAccessPolicyClientListByAuthorizationResponse])
}

// NewAuthorizationAccessPolicyServerTransport creates a new instance of AuthorizationAccessPolicyServerTransport with the provided implementation.
// The returned AuthorizationAccessPolicyServerTransport instance is connected to an instance of armapimanagement.AuthorizationAccessPolicyClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewAuthorizationAccessPolicyServerTransport(srv *AuthorizationAccessPolicyServer) *AuthorizationAccessPolicyServerTransport {
	return &AuthorizationAccessPolicyServerTransport{
		srv:                         srv,
		newListByAuthorizationPager: newTracker[azfake.PagerResponder[armapimanagement.AuthorizationAccessPolicyClientListByAuthorizationResponse]](),
	}
}

// AuthorizationAccessPolicyServerTransport connects instances of armapimanagement.AuthorizationAccessPolicyClient to instances of AuthorizationAccessPolicyServer.
// Don't use this type directly, use NewAuthorizationAccessPolicyServerTransport instead.
type AuthorizationAccessPolicyServerTransport struct {
	srv                         *AuthorizationAccessPolicyServer
	newListByAuthorizationPager *tracker[azfake.PagerResponder[armapimanagement.AuthorizationAccessPolicyClientListByAuthorizationResponse]]
}

// Do implements the policy.Transporter interface for AuthorizationAccessPolicyServerTransport.
func (a *AuthorizationAccessPolicyServerTransport) 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 *AuthorizationAccessPolicyServerTransport) 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 authorizationAccessPolicyServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = authorizationAccessPolicyServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "AuthorizationAccessPolicyClient.CreateOrUpdate":
				res.resp, res.err = a.dispatchCreateOrUpdate(req)
			case "AuthorizationAccessPolicyClient.Delete":
				res.resp, res.err = a.dispatchDelete(req)
			case "AuthorizationAccessPolicyClient.Get":
				res.resp, res.err = a.dispatchGet(req)
			case "AuthorizationAccessPolicyClient.NewListByAuthorizationPager":
				res.resp, res.err = a.dispatchNewListByAuthorizationPager(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 *AuthorizationAccessPolicyServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if a.srv.CreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiManagement/service/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/authorizationProviders/(?P<authorizationProviderId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/authorizations/(?P<authorizationId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/accessPolicies/(?P<authorizationAccessPolicyId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 6 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armapimanagement.AuthorizationAccessPolicyContract](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
	if err != nil {
		return nil, err
	}
	authorizationProviderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("authorizationProviderId")])
	if err != nil {
		return nil, err
	}
	authorizationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("authorizationId")])
	if err != nil {
		return nil, err
	}
	authorizationAccessPolicyIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("authorizationAccessPolicyId")])
	if err != nil {
		return nil, err
	}
	ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
	var options *armapimanagement.AuthorizationAccessPolicyClientCreateOrUpdateOptions
	if ifMatchParam != nil {
		options = &armapimanagement.AuthorizationAccessPolicyClientCreateOrUpdateOptions{
			IfMatch: ifMatchParam,
		}
	}
	respr, errRespr := a.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, serviceNameParam, authorizationProviderIDParam, authorizationIDParam, authorizationAccessPolicyIDParam, body, options)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AuthorizationAccessPolicyContract, req)
	if err != nil {
		return nil, err
	}
	if val := server.GetResponse(respr).ETag; val != nil {
		resp.Header.Set("ETag", *val)
	}
	return resp, nil
}

func (a *AuthorizationAccessPolicyServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if a.srv.Delete == nil {
		return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiManagement/service/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/authorizationProviders/(?P<authorizationProviderId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/authorizations/(?P<authorizationId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/accessPolicies/(?P<authorizationAccessPolicyId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 6 {
		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
	}
	serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
	if err != nil {
		return nil, err
	}
	authorizationProviderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("authorizationProviderId")])
	if err != nil {
		return nil, err
	}
	authorizationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("authorizationId")])
	if err != nil {
		return nil, err
	}
	authorizationAccessPolicyIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("authorizationAccessPolicyId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := a.srv.Delete(req.Context(), resourceGroupNameParam, serviceNameParam, authorizationProviderIDParam, authorizationIDParam, authorizationAccessPolicyIDParam, getHeaderValue(req.Header, "If-Match"), nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)}
	}
	resp, err := server.NewResponse(respContent, req, nil)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *AuthorizationAccessPolicyServerTransport) 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/service/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/authorizationProviders/(?P<authorizationProviderId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/authorizations/(?P<authorizationId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/accessPolicies/(?P<authorizationAccessPolicyId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 6 {
		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
	}
	serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
	if err != nil {
		return nil, err
	}
	authorizationProviderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("authorizationProviderId")])
	if err != nil {
		return nil, err
	}
	authorizationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("authorizationId")])
	if err != nil {
		return nil, err
	}
	authorizationAccessPolicyIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("authorizationAccessPolicyId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, serviceNameParam, authorizationProviderIDParam, authorizationIDParam, authorizationAccessPolicyIDParam, 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).AuthorizationAccessPolicyContract, req)
	if err != nil {
		return nil, err
	}
	if val := server.GetResponse(respr).ETag; val != nil {
		resp.Header.Set("ETag", *val)
	}
	return resp, nil
}

func (a *AuthorizationAccessPolicyServerTransport) dispatchNewListByAuthorizationPager(req *http.Request) (*http.Response, error) {
	if a.srv.NewListByAuthorizationPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByAuthorizationPager not implemented")}
	}
	newListByAuthorizationPager := a.newListByAuthorizationPager.get(req)
	if newListByAuthorizationPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiManagement/service/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/authorizationProviders/(?P<authorizationProviderId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/authorizations/(?P<authorizationId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/accessPolicies`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 5 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		qp := req.URL.Query()
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
		if err != nil {
			return nil, err
		}
		authorizationProviderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("authorizationProviderId")])
		if err != nil {
			return nil, err
		}
		authorizationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("authorizationId")])
		if err != nil {
			return nil, err
		}
		filterUnescaped, err := url.QueryUnescape(qp.Get("$filter"))
		if err != nil {
			return nil, err
		}
		filterParam := getOptional(filterUnescaped)
		topUnescaped, err := url.QueryUnescape(qp.Get("$top"))
		if err != nil {
			return nil, err
		}
		topParam, err := parseOptional(topUnescaped, func(v string) (int32, error) {
			p, parseErr := strconv.ParseInt(v, 10, 32)
			if parseErr != nil {
				return 0, parseErr
			}
			return int32(p), nil
		})
		if err != nil {
			return nil, err
		}
		skipUnescaped, err := url.QueryUnescape(qp.Get("$skip"))
		if err != nil {
			return nil, err
		}
		skipParam, err := parseOptional(skipUnescaped, func(v string) (int32, error) {
			p, parseErr := strconv.ParseInt(v, 10, 32)
			if parseErr != nil {
				return 0, parseErr
			}
			return int32(p), nil
		})
		if err != nil {
			return nil, err
		}
		var options *armapimanagement.AuthorizationAccessPolicyClientListByAuthorizationOptions
		if filterParam != nil || topParam != nil || skipParam != nil {
			options = &armapimanagement.AuthorizationAccessPolicyClientListByAuthorizationOptions{
				Filter: filterParam,
				Top:    topParam,
				Skip:   skipParam,
			}
		}
		resp := a.srv.NewListByAuthorizationPager(resourceGroupNameParam, serviceNameParam, authorizationProviderIDParam, authorizationIDParam, options)
		newListByAuthorizationPager = &resp
		a.newListByAuthorizationPager.add(req, newListByAuthorizationPager)
		server.PagerResponderInjectNextLinks(newListByAuthorizationPager, req, func(page *armapimanagement.AuthorizationAccessPolicyClientListByAuthorizationResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByAuthorizationPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		a.newListByAuthorizationPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByAuthorizationPager) {
		a.newListByAuthorizationPager.remove(req)
	}
	return resp, nil
}

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