// 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/storagecache/armstoragecache/v4"
	"net/http"
	"net/url"
	"regexp"
)

// StorageTargetsServer is a fake server for instances of the armstoragecache.StorageTargetsClient type.
type StorageTargetsServer struct {
	// BeginCreateOrUpdate is the fake for method StorageTargetsClient.BeginCreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated, http.StatusAccepted
	BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, cacheName string, storageTargetName string, storagetarget armstoragecache.StorageTarget, options *armstoragecache.StorageTargetsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armstoragecache.StorageTargetsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// BeginDNSRefresh is the fake for method StorageTargetsClient.BeginDNSRefresh
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDNSRefresh func(ctx context.Context, resourceGroupName string, cacheName string, storageTargetName string, options *armstoragecache.StorageTargetsClientBeginDNSRefreshOptions) (resp azfake.PollerResponder[armstoragecache.StorageTargetsClientDNSRefreshResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method StorageTargetsClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, cacheName string, storageTargetName string, options *armstoragecache.StorageTargetsClientBeginDeleteOptions) (resp azfake.PollerResponder[armstoragecache.StorageTargetsClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method StorageTargetsClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, cacheName string, storageTargetName string, options *armstoragecache.StorageTargetsClientGetOptions) (resp azfake.Responder[armstoragecache.StorageTargetsClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByCachePager is the fake for method StorageTargetsClient.NewListByCachePager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByCachePager func(resourceGroupName string, cacheName string, options *armstoragecache.StorageTargetsClientListByCacheOptions) (resp azfake.PagerResponder[armstoragecache.StorageTargetsClientListByCacheResponse])

	// BeginRestoreDefaults is the fake for method StorageTargetsClient.BeginRestoreDefaults
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginRestoreDefaults func(ctx context.Context, resourceGroupName string, cacheName string, storageTargetName string, options *armstoragecache.StorageTargetsClientBeginRestoreDefaultsOptions) (resp azfake.PollerResponder[armstoragecache.StorageTargetsClientRestoreDefaultsResponse], errResp azfake.ErrorResponder)
}

// NewStorageTargetsServerTransport creates a new instance of StorageTargetsServerTransport with the provided implementation.
// The returned StorageTargetsServerTransport instance is connected to an instance of armstoragecache.StorageTargetsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewStorageTargetsServerTransport(srv *StorageTargetsServer) *StorageTargetsServerTransport {
	return &StorageTargetsServerTransport{
		srv:                  srv,
		beginCreateOrUpdate:  newTracker[azfake.PollerResponder[armstoragecache.StorageTargetsClientCreateOrUpdateResponse]](),
		beginDNSRefresh:      newTracker[azfake.PollerResponder[armstoragecache.StorageTargetsClientDNSRefreshResponse]](),
		beginDelete:          newTracker[azfake.PollerResponder[armstoragecache.StorageTargetsClientDeleteResponse]](),
		newListByCachePager:  newTracker[azfake.PagerResponder[armstoragecache.StorageTargetsClientListByCacheResponse]](),
		beginRestoreDefaults: newTracker[azfake.PollerResponder[armstoragecache.StorageTargetsClientRestoreDefaultsResponse]](),
	}
}

// StorageTargetsServerTransport connects instances of armstoragecache.StorageTargetsClient to instances of StorageTargetsServer.
// Don't use this type directly, use NewStorageTargetsServerTransport instead.
type StorageTargetsServerTransport struct {
	srv                  *StorageTargetsServer
	beginCreateOrUpdate  *tracker[azfake.PollerResponder[armstoragecache.StorageTargetsClientCreateOrUpdateResponse]]
	beginDNSRefresh      *tracker[azfake.PollerResponder[armstoragecache.StorageTargetsClientDNSRefreshResponse]]
	beginDelete          *tracker[azfake.PollerResponder[armstoragecache.StorageTargetsClientDeleteResponse]]
	newListByCachePager  *tracker[azfake.PagerResponder[armstoragecache.StorageTargetsClientListByCacheResponse]]
	beginRestoreDefaults *tracker[azfake.PollerResponder[armstoragecache.StorageTargetsClientRestoreDefaultsResponse]]
}

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

func (s *StorageTargetsServerTransport) 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 storageTargetsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = storageTargetsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "StorageTargetsClient.BeginCreateOrUpdate":
				res.resp, res.err = s.dispatchBeginCreateOrUpdate(req)
			case "StorageTargetsClient.BeginDNSRefresh":
				res.resp, res.err = s.dispatchBeginDNSRefresh(req)
			case "StorageTargetsClient.BeginDelete":
				res.resp, res.err = s.dispatchBeginDelete(req)
			case "StorageTargetsClient.Get":
				res.resp, res.err = s.dispatchGet(req)
			case "StorageTargetsClient.NewListByCachePager":
				res.resp, res.err = s.dispatchNewListByCachePager(req)
			case "StorageTargetsClient.BeginRestoreDefaults":
				res.resp, res.err = s.dispatchBeginRestoreDefaults(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 (s *StorageTargetsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if s.srv.BeginCreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")}
	}
	beginCreateOrUpdate := s.beginCreateOrUpdate.get(req)
	if beginCreateOrUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourcegroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.StorageCache/caches/(?P<cacheName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/storageTargets/(?P<storageTargetName>[!#&$-;=?-\[\]_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[armstoragecache.StorageTarget](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		cacheNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cacheName")])
		if err != nil {
			return nil, err
		}
		storageTargetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("storageTargetName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := s.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, cacheNameParam, storageTargetNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateOrUpdate = &respr
		s.beginCreateOrUpdate.add(req, beginCreateOrUpdate)
	}

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

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

	return resp, nil
}

func (s *StorageTargetsServerTransport) dispatchBeginDNSRefresh(req *http.Request) (*http.Response, error) {
	if s.srv.BeginDNSRefresh == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDNSRefresh not implemented")}
	}
	beginDNSRefresh := s.beginDNSRefresh.get(req)
	if beginDNSRefresh == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourcegroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.StorageCache/caches/(?P<cacheName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/storageTargets/(?P<storageTargetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dnsRefresh`
		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
		}
		cacheNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cacheName")])
		if err != nil {
			return nil, err
		}
		storageTargetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("storageTargetName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := s.srv.BeginDNSRefresh(req.Context(), resourceGroupNameParam, cacheNameParam, storageTargetNameParam, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDNSRefresh = &respr
		s.beginDNSRefresh.add(req, beginDNSRefresh)
	}

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

	if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) {
		s.beginDNSRefresh.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(beginDNSRefresh) {
		s.beginDNSRefresh.remove(req)
	}

	return resp, nil
}

func (s *StorageTargetsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if s.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := s.beginDelete.get(req)
	if beginDelete == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourcegroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.StorageCache/caches/(?P<cacheName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/storageTargets/(?P<storageTargetName>[!#&$-;=?-\[\]_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)
		}
		qp := req.URL.Query()
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		cacheNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cacheName")])
		if err != nil {
			return nil, err
		}
		storageTargetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("storageTargetName")])
		if err != nil {
			return nil, err
		}
		forceUnescaped, err := url.QueryUnescape(qp.Get("force"))
		if err != nil {
			return nil, err
		}
		forceParam := getOptional(forceUnescaped)
		var options *armstoragecache.StorageTargetsClientBeginDeleteOptions
		if forceParam != nil {
			options = &armstoragecache.StorageTargetsClientBeginDeleteOptions{
				Force: forceParam,
			}
		}
		respr, errRespr := s.srv.BeginDelete(req.Context(), resourceGroupNameParam, cacheNameParam, storageTargetNameParam, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		s.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) {
		s.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) {
		s.beginDelete.remove(req)
	}

	return resp, nil
}

func (s *StorageTargetsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if s.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\.StorageCache/caches/(?P<cacheName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/storageTargets/(?P<storageTargetName>[!#&$-;=?-\[\]_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
	}
	cacheNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cacheName")])
	if err != nil {
		return nil, err
	}
	storageTargetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("storageTargetName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.Get(req.Context(), resourceGroupNameParam, cacheNameParam, storageTargetNameParam, 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).StorageTarget, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (s *StorageTargetsServerTransport) dispatchNewListByCachePager(req *http.Request) (*http.Response, error) {
	if s.srv.NewListByCachePager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByCachePager not implemented")}
	}
	newListByCachePager := s.newListByCachePager.get(req)
	if newListByCachePager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourcegroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.StorageCache/caches/(?P<cacheName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/storageTargets`
		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
		}
		cacheNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cacheName")])
		if err != nil {
			return nil, err
		}
		resp := s.srv.NewListByCachePager(resourceGroupNameParam, cacheNameParam, nil)
		newListByCachePager = &resp
		s.newListByCachePager.add(req, newListByCachePager)
		server.PagerResponderInjectNextLinks(newListByCachePager, req, func(page *armstoragecache.StorageTargetsClientListByCacheResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByCachePager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		s.newListByCachePager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByCachePager) {
		s.newListByCachePager.remove(req)
	}
	return resp, nil
}

func (s *StorageTargetsServerTransport) dispatchBeginRestoreDefaults(req *http.Request) (*http.Response, error) {
	if s.srv.BeginRestoreDefaults == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginRestoreDefaults not implemented")}
	}
	beginRestoreDefaults := s.beginRestoreDefaults.get(req)
	if beginRestoreDefaults == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.StorageCache/caches/(?P<cacheName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/storageTargets/(?P<storageTargetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/restoreDefaults`
		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
		}
		cacheNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cacheName")])
		if err != nil {
			return nil, err
		}
		storageTargetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("storageTargetName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := s.srv.BeginRestoreDefaults(req.Context(), resourceGroupNameParam, cacheNameParam, storageTargetNameParam, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginRestoreDefaults = &respr
		s.beginRestoreDefaults.add(req, beginRestoreDefaults)
	}

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

	if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) {
		s.beginRestoreDefaults.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(beginRestoreDefaults) {
		s.beginRestoreDefaults.remove(req)
	}

	return resp, nil
}

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