// 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/appconfiguration/armappconfiguration/v3"
	"net/http"
	"net/url"
	"regexp"
	"slices"
)

// ReplicasServer is a fake server for instances of the armappconfiguration.ReplicasClient type.
type ReplicasServer struct {
	// BeginCreate is the fake for method ReplicasClient.BeginCreate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	BeginCreate func(ctx context.Context, resourceGroupName string, configStoreName string, replicaName string, replicaCreationParameters armappconfiguration.Replica, options *armappconfiguration.ReplicasClientBeginCreateOptions) (resp azfake.PollerResponder[armappconfiguration.ReplicasClientCreateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method ReplicasClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, configStoreName string, replicaName string, options *armappconfiguration.ReplicasClientBeginDeleteOptions) (resp azfake.PollerResponder[armappconfiguration.ReplicasClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method ReplicasClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, configStoreName string, replicaName string, options *armappconfiguration.ReplicasClientGetOptions) (resp azfake.Responder[armappconfiguration.ReplicasClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByConfigurationStorePager is the fake for method ReplicasClient.NewListByConfigurationStorePager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByConfigurationStorePager func(resourceGroupName string, configStoreName string, options *armappconfiguration.ReplicasClientListByConfigurationStoreOptions) (resp azfake.PagerResponder[armappconfiguration.ReplicasClientListByConfigurationStoreResponse])
}

// NewReplicasServerTransport creates a new instance of ReplicasServerTransport with the provided implementation.
// The returned ReplicasServerTransport instance is connected to an instance of armappconfiguration.ReplicasClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewReplicasServerTransport(srv *ReplicasServer) *ReplicasServerTransport {
	return &ReplicasServerTransport{
		srv:                              srv,
		beginCreate:                      newTracker[azfake.PollerResponder[armappconfiguration.ReplicasClientCreateResponse]](),
		beginDelete:                      newTracker[azfake.PollerResponder[armappconfiguration.ReplicasClientDeleteResponse]](),
		newListByConfigurationStorePager: newTracker[azfake.PagerResponder[armappconfiguration.ReplicasClientListByConfigurationStoreResponse]](),
	}
}

// ReplicasServerTransport connects instances of armappconfiguration.ReplicasClient to instances of ReplicasServer.
// Don't use this type directly, use NewReplicasServerTransport instead.
type ReplicasServerTransport struct {
	srv                              *ReplicasServer
	beginCreate                      *tracker[azfake.PollerResponder[armappconfiguration.ReplicasClientCreateResponse]]
	beginDelete                      *tracker[azfake.PollerResponder[armappconfiguration.ReplicasClientDeleteResponse]]
	newListByConfigurationStorePager *tracker[azfake.PagerResponder[armappconfiguration.ReplicasClientListByConfigurationStoreResponse]]
}

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

func (r *ReplicasServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if replicasServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = replicasServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "ReplicasClient.BeginCreate":
				res.resp, res.err = r.dispatchBeginCreate(req)
			case "ReplicasClient.BeginDelete":
				res.resp, res.err = r.dispatchBeginDelete(req)
			case "ReplicasClient.Get":
				res.resp, res.err = r.dispatchGet(req)
			case "ReplicasClient.NewListByConfigurationStorePager":
				res.resp, res.err = r.dispatchNewListByConfigurationStorePager(req)
			default:
				res.err = fmt.Errorf("unhandled API %s", method)
			}

		}
		resultChan <- res
	}()

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

func (r *ReplicasServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) {
	if r.srv.BeginCreate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")}
	}
	beginCreate := r.beginCreate.get(req)
	if beginCreate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AppConfiguration/configurationStores/(?P<configStoreName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/replicas/(?P<replicaName>[!#&$-;=?-\[\]_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[armappconfiguration.Replica](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		configStoreNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("configStoreName")])
		if err != nil {
			return nil, err
		}
		replicaNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("replicaName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := r.srv.BeginCreate(req.Context(), resourceGroupNameParam, configStoreNameParam, replicaNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreate = &respr
		r.beginCreate.add(req, beginCreate)
	}

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

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

	return resp, nil
}

func (r *ReplicasServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if r.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := r.beginDelete.get(req)
	if beginDelete == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AppConfiguration/configurationStores/(?P<configStoreName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/replicas/(?P<replicaName>[!#&$-;=?-\[\]_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
		}
		configStoreNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("configStoreName")])
		if err != nil {
			return nil, err
		}
		replicaNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("replicaName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := r.srv.BeginDelete(req.Context(), resourceGroupNameParam, configStoreNameParam, replicaNameParam, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		r.beginDelete.add(req, beginDelete)
	}

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

	if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) {
		r.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) {
		r.beginDelete.remove(req)
	}

	return resp, nil
}

func (r *ReplicasServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if r.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\.AppConfiguration/configurationStores/(?P<configStoreName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/replicas/(?P<replicaName>[!#&$-;=?-\[\]_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
	}
	configStoreNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("configStoreName")])
	if err != nil {
		return nil, err
	}
	replicaNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("replicaName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := r.srv.Get(req.Context(), resourceGroupNameParam, configStoreNameParam, replicaNameParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !slices.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).Replica, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (r *ReplicasServerTransport) dispatchNewListByConfigurationStorePager(req *http.Request) (*http.Response, error) {
	if r.srv.NewListByConfigurationStorePager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByConfigurationStorePager not implemented")}
	}
	newListByConfigurationStorePager := r.newListByConfigurationStorePager.get(req)
	if newListByConfigurationStorePager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AppConfiguration/configurationStores/(?P<configStoreName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/replicas`
		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)
		}
		qp := req.URL.Query()
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		configStoreNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("configStoreName")])
		if err != nil {
			return nil, err
		}
		skipTokenParam := getOptional(qp.Get("$skipToken"))
		var options *armappconfiguration.ReplicasClientListByConfigurationStoreOptions
		if skipTokenParam != nil {
			options = &armappconfiguration.ReplicasClientListByConfigurationStoreOptions{
				SkipToken: skipTokenParam,
			}
		}
		resp := r.srv.NewListByConfigurationStorePager(resourceGroupNameParam, configStoreNameParam, options)
		newListByConfigurationStorePager = &resp
		r.newListByConfigurationStorePager.add(req, newListByConfigurationStorePager)
		server.PagerResponderInjectNextLinks(newListByConfigurationStorePager, req, func(page *armappconfiguration.ReplicasClientListByConfigurationStoreResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByConfigurationStorePager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		r.newListByConfigurationStorePager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByConfigurationStorePager) {
		r.newListByConfigurationStorePager.remove(req)
	}
	return resp, nil
}

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