// 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) Go Code Generator. DO NOT EDIT.

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/mongocluster/armmongocluster"
	"net/http"
	"net/url"
	"regexp"
)

// UsersServer is a fake server for instances of the armmongocluster.UsersClient type.
type UsersServer struct {
	// BeginCreateOrUpdate is the fake for method UsersClient.BeginCreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, resource armmongocluster.User, options *armmongocluster.UsersClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armmongocluster.UsersClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method UsersClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, options *armmongocluster.UsersClientBeginDeleteOptions) (resp azfake.PollerResponder[armmongocluster.UsersClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method UsersClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, options *armmongocluster.UsersClientGetOptions) (resp azfake.Responder[armmongocluster.UsersClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByMongoClusterPager is the fake for method UsersClient.NewListByMongoClusterPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByMongoClusterPager func(resourceGroupName string, mongoClusterName string, options *armmongocluster.UsersClientListByMongoClusterOptions) (resp azfake.PagerResponder[armmongocluster.UsersClientListByMongoClusterResponse])
}

// NewUsersServerTransport creates a new instance of UsersServerTransport with the provided implementation.
// The returned UsersServerTransport instance is connected to an instance of armmongocluster.UsersClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewUsersServerTransport(srv *UsersServer) *UsersServerTransport {
	return &UsersServerTransport{
		srv:                        srv,
		beginCreateOrUpdate:        newTracker[azfake.PollerResponder[armmongocluster.UsersClientCreateOrUpdateResponse]](),
		beginDelete:                newTracker[azfake.PollerResponder[armmongocluster.UsersClientDeleteResponse]](),
		newListByMongoClusterPager: newTracker[azfake.PagerResponder[armmongocluster.UsersClientListByMongoClusterResponse]](),
	}
}

// UsersServerTransport connects instances of armmongocluster.UsersClient to instances of UsersServer.
// Don't use this type directly, use NewUsersServerTransport instead.
type UsersServerTransport struct {
	srv                        *UsersServer
	beginCreateOrUpdate        *tracker[azfake.PollerResponder[armmongocluster.UsersClientCreateOrUpdateResponse]]
	beginDelete                *tracker[azfake.PollerResponder[armmongocluster.UsersClientDeleteResponse]]
	newListByMongoClusterPager *tracker[azfake.PagerResponder[armmongocluster.UsersClientListByMongoClusterResponse]]
}

// Do implements the policy.Transporter interface for UsersServerTransport.
func (u *UsersServerTransport) 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 u.dispatchToMethodFake(req, method)
}

func (u *UsersServerTransport) 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 usersServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = usersServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "UsersClient.BeginCreateOrUpdate":
				res.resp, res.err = u.dispatchBeginCreateOrUpdate(req)
			case "UsersClient.BeginDelete":
				res.resp, res.err = u.dispatchBeginDelete(req)
			case "UsersClient.Get":
				res.resp, res.err = u.dispatchGet(req)
			case "UsersClient.NewListByMongoClusterPager":
				res.resp, res.err = u.dispatchNewListByMongoClusterPager(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 (u *UsersServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if u.srv.BeginCreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")}
	}
	beginCreateOrUpdate := u.beginCreateOrUpdate.get(req)
	if beginCreateOrUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P<mongoClusterName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/users/(?P<userName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 5 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		body, err := server.UnmarshalRequestAsJSON[armmongocluster.User](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")])
		if err != nil {
			return nil, err
		}
		userNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("userName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := u.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, mongoClusterNameParam, userNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateOrUpdate = &respr
		u.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) {
		u.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) {
		u.beginCreateOrUpdate.remove(req)
	}

	return resp, nil
}

func (u *UsersServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if u.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := u.beginDelete.get(req)
	if beginDelete == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P<mongoClusterName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/users/(?P<userName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if 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
		}
		mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")])
		if err != nil {
			return nil, err
		}
		userNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("userName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := u.srv.BeginDelete(req.Context(), resourceGroupNameParam, mongoClusterNameParam, userNameParam, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		u.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) {
		u.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) {
		u.beginDelete.remove(req)
	}

	return resp, nil
}

func (u *UsersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if u.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\.DocumentDB/mongoClusters/(?P<mongoClusterName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/users/(?P<userName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if 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
	}
	mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")])
	if err != nil {
		return nil, err
	}
	userNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("userName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := u.srv.Get(req.Context(), resourceGroupNameParam, mongoClusterNameParam, userNameParam, 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).User, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (u *UsersServerTransport) dispatchNewListByMongoClusterPager(req *http.Request) (*http.Response, error) {
	if u.srv.NewListByMongoClusterPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByMongoClusterPager not implemented")}
	}
	newListByMongoClusterPager := u.newListByMongoClusterPager.get(req)
	if newListByMongoClusterPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P<mongoClusterName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/users`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if 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
		}
		mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")])
		if err != nil {
			return nil, err
		}
		resp := u.srv.NewListByMongoClusterPager(resourceGroupNameParam, mongoClusterNameParam, nil)
		newListByMongoClusterPager = &resp
		u.newListByMongoClusterPager.add(req, newListByMongoClusterPager)
		server.PagerResponderInjectNextLinks(newListByMongoClusterPager, req, func(page *armmongocluster.UsersClientListByMongoClusterResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByMongoClusterPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		u.newListByMongoClusterPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByMongoClusterPager) {
		u.newListByMongoClusterPager.remove(req)
	}
	return resp, nil
}

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