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

// KeyValuesServer is a fake server for instances of the armappconfiguration.KeyValuesClient type.
type KeyValuesServer struct {
	// CreateOrUpdate is the fake for method KeyValuesClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK
	CreateOrUpdate func(ctx context.Context, resourceGroupName string, configStoreName string, keyValueName string, keyValueParameters armappconfiguration.KeyValue, options *armappconfiguration.KeyValuesClientCreateOrUpdateOptions) (resp azfake.Responder[armappconfiguration.KeyValuesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

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

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

// NewKeyValuesServerTransport creates a new instance of KeyValuesServerTransport with the provided implementation.
// The returned KeyValuesServerTransport instance is connected to an instance of armappconfiguration.KeyValuesClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewKeyValuesServerTransport(srv *KeyValuesServer) *KeyValuesServerTransport {
	return &KeyValuesServerTransport{
		srv:         srv,
		beginDelete: newTracker[azfake.PollerResponder[armappconfiguration.KeyValuesClientDeleteResponse]](),
	}
}

// KeyValuesServerTransport connects instances of armappconfiguration.KeyValuesClient to instances of KeyValuesServer.
// Don't use this type directly, use NewKeyValuesServerTransport instead.
type KeyValuesServerTransport struct {
	srv         *KeyValuesServer
	beginDelete *tracker[azfake.PollerResponder[armappconfiguration.KeyValuesClientDeleteResponse]]
}

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

func (k *KeyValuesServerTransport) 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 keyValuesServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = keyValuesServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "KeyValuesClient.CreateOrUpdate":
				res.resp, res.err = k.dispatchCreateOrUpdate(req)
			case "KeyValuesClient.BeginDelete":
				res.resp, res.err = k.dispatchBeginDelete(req)
			case "KeyValuesClient.Get":
				res.resp, res.err = k.dispatchGet(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 (k *KeyValuesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if k.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\.AppConfiguration/configurationStores/(?P<configStoreName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/keyValues/(?P<keyValueName>[!#&$-;=?-\[\]_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[armappconfiguration.KeyValue](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
	}
	keyValueNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("keyValueName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := k.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, configStoreNameParam, keyValueNameParam, body, 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).KeyValue, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (k *KeyValuesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if k.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := k.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~%@]+)/keyValues/(?P<keyValueName>[!#&$-;=?-\[\]_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
		}
		configStoreNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("configStoreName")])
		if err != nil {
			return nil, err
		}
		keyValueNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("keyValueName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := k.srv.BeginDelete(req.Context(), resourceGroupNameParam, configStoreNameParam, keyValueNameParam, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		k.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) {
		k.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) {
		k.beginDelete.remove(req)
	}

	return resp, nil
}

func (k *KeyValuesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if k.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~%@]+)/keyValues/(?P<keyValueName>[!#&$-;=?-\[\]_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
	}
	configStoreNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("configStoreName")])
	if err != nil {
		return nil, err
	}
	keyValueNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("keyValueName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := k.srv.Get(req.Context(), resourceGroupNameParam, configStoreNameParam, keyValueNameParam, 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).KeyValue, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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