// 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/redisenterprise/armredisenterprise/v2"
	"net/http"
	"net/url"
	"regexp"
)

// AccessPolicyAssignmentServer is a fake server for instances of the armredisenterprise.AccessPolicyAssignmentClient type.
type AccessPolicyAssignmentServer struct {
	// BeginCreateUpdate is the fake for method AccessPolicyAssignmentClient.BeginCreateUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	BeginCreateUpdate func(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, accessPolicyAssignmentName string, parameters armredisenterprise.AccessPolicyAssignment, options *armredisenterprise.AccessPolicyAssignmentClientBeginCreateUpdateOptions) (resp azfake.PollerResponder[armredisenterprise.AccessPolicyAssignmentClientCreateUpdateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method AccessPolicyAssignmentClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, accessPolicyAssignmentName string, options *armredisenterprise.AccessPolicyAssignmentClientBeginDeleteOptions) (resp azfake.PollerResponder[armredisenterprise.AccessPolicyAssignmentClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method AccessPolicyAssignmentClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, accessPolicyAssignmentName string, options *armredisenterprise.AccessPolicyAssignmentClientGetOptions) (resp azfake.Responder[armredisenterprise.AccessPolicyAssignmentClientGetResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method AccessPolicyAssignmentClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(resourceGroupName string, clusterName string, databaseName string, options *armredisenterprise.AccessPolicyAssignmentClientListOptions) (resp azfake.PagerResponder[armredisenterprise.AccessPolicyAssignmentClientListResponse])
}

// NewAccessPolicyAssignmentServerTransport creates a new instance of AccessPolicyAssignmentServerTransport with the provided implementation.
// The returned AccessPolicyAssignmentServerTransport instance is connected to an instance of armredisenterprise.AccessPolicyAssignmentClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewAccessPolicyAssignmentServerTransport(srv *AccessPolicyAssignmentServer) *AccessPolicyAssignmentServerTransport {
	return &AccessPolicyAssignmentServerTransport{
		srv:               srv,
		beginCreateUpdate: newTracker[azfake.PollerResponder[armredisenterprise.AccessPolicyAssignmentClientCreateUpdateResponse]](),
		beginDelete:       newTracker[azfake.PollerResponder[armredisenterprise.AccessPolicyAssignmentClientDeleteResponse]](),
		newListPager:      newTracker[azfake.PagerResponder[armredisenterprise.AccessPolicyAssignmentClientListResponse]](),
	}
}

// AccessPolicyAssignmentServerTransport connects instances of armredisenterprise.AccessPolicyAssignmentClient to instances of AccessPolicyAssignmentServer.
// Don't use this type directly, use NewAccessPolicyAssignmentServerTransport instead.
type AccessPolicyAssignmentServerTransport struct {
	srv               *AccessPolicyAssignmentServer
	beginCreateUpdate *tracker[azfake.PollerResponder[armredisenterprise.AccessPolicyAssignmentClientCreateUpdateResponse]]
	beginDelete       *tracker[azfake.PollerResponder[armredisenterprise.AccessPolicyAssignmentClientDeleteResponse]]
	newListPager      *tracker[azfake.PagerResponder[armredisenterprise.AccessPolicyAssignmentClientListResponse]]
}

// Do implements the policy.Transporter interface for AccessPolicyAssignmentServerTransport.
func (a *AccessPolicyAssignmentServerTransport) 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 *AccessPolicyAssignmentServerTransport) 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 accessPolicyAssignmentServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = accessPolicyAssignmentServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "AccessPolicyAssignmentClient.BeginCreateUpdate":
				res.resp, res.err = a.dispatchBeginCreateUpdate(req)
			case "AccessPolicyAssignmentClient.BeginDelete":
				res.resp, res.err = a.dispatchBeginDelete(req)
			case "AccessPolicyAssignmentClient.Get":
				res.resp, res.err = a.dispatchGet(req)
			case "AccessPolicyAssignmentClient.NewListPager":
				res.resp, res.err = a.dispatchNewListPager(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 *AccessPolicyAssignmentServerTransport) dispatchBeginCreateUpdate(req *http.Request) (*http.Response, error) {
	if a.srv.BeginCreateUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateUpdate not implemented")}
	}
	beginCreateUpdate := a.beginCreateUpdate.get(req)
	if beginCreateUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Cache/redisEnterprise/(?P<clusterName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P<databaseName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/accessPolicyAssignments/(?P<accessPolicyAssignmentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		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)
		}
		body, err := server.UnmarshalRequestAsJSON[armredisenterprise.AccessPolicyAssignment](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		clusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("clusterName")])
		if err != nil {
			return nil, err
		}
		databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")])
		if err != nil {
			return nil, err
		}
		accessPolicyAssignmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accessPolicyAssignmentName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := a.srv.BeginCreateUpdate(req.Context(), resourceGroupNameParam, clusterNameParam, databaseNameParam, accessPolicyAssignmentNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateUpdate = &respr
		a.beginCreateUpdate.add(req, beginCreateUpdate)
	}

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

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

	return resp, nil
}

func (a *AccessPolicyAssignmentServerTransport) 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\.Cache/redisEnterprise/(?P<clusterName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P<databaseName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/accessPolicyAssignments/(?P<accessPolicyAssignmentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		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)
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		clusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("clusterName")])
		if err != nil {
			return nil, err
		}
		databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")])
		if err != nil {
			return nil, err
		}
		accessPolicyAssignmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accessPolicyAssignmentName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := a.srv.BeginDelete(req.Context(), resourceGroupNameParam, clusterNameParam, databaseNameParam, accessPolicyAssignmentNameParam, 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 *AccessPolicyAssignmentServerTransport) 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\.Cache/redisEnterprise/(?P<clusterName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P<databaseName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/accessPolicyAssignments/(?P<accessPolicyAssignmentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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)
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	clusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("clusterName")])
	if err != nil {
		return nil, err
	}
	databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")])
	if err != nil {
		return nil, err
	}
	accessPolicyAssignmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accessPolicyAssignmentName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, clusterNameParam, databaseNameParam, accessPolicyAssignmentNameParam, 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).AccessPolicyAssignment, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *AccessPolicyAssignmentServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if a.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := a.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Cache/redisEnterprise/(?P<clusterName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P<databaseName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/accessPolicyAssignments`
		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
		}
		clusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("clusterName")])
		if err != nil {
			return nil, err
		}
		databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")])
		if err != nil {
			return nil, err
		}
		resp := a.srv.NewListPager(resourceGroupNameParam, clusterNameParam, databaseNameParam, nil)
		newListPager = &resp
		a.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armredisenterprise.AccessPolicyAssignmentClientListResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		a.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		a.newListPager.remove(req)
	}
	return resp, nil
}

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