// 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/resources/armresources/v3"
	"net/http"
	"net/url"
	"regexp"
)

// TagsServer is a fake server for instances of the armresources.TagsClient type.
type TagsServer struct {
	// CreateOrUpdate is the fake for method TagsClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrUpdate func(ctx context.Context, tagName string, options *armresources.TagsClientCreateOrUpdateOptions) (resp azfake.Responder[armresources.TagsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// BeginCreateOrUpdateAtScope is the fake for method TagsClient.BeginCreateOrUpdateAtScope
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginCreateOrUpdateAtScope func(ctx context.Context, scope string, parameters armresources.TagsResource, options *armresources.TagsClientBeginCreateOrUpdateAtScopeOptions) (resp azfake.PollerResponder[armresources.TagsClientCreateOrUpdateAtScopeResponse], errResp azfake.ErrorResponder)

	// CreateOrUpdateValue is the fake for method TagsClient.CreateOrUpdateValue
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrUpdateValue func(ctx context.Context, tagName string, tagValue string, options *armresources.TagsClientCreateOrUpdateValueOptions) (resp azfake.Responder[armresources.TagsClientCreateOrUpdateValueResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method TagsClient.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, tagName string, options *armresources.TagsClientDeleteOptions) (resp azfake.Responder[armresources.TagsClientDeleteResponse], errResp azfake.ErrorResponder)

	// BeginDeleteAtScope is the fake for method TagsClient.BeginDeleteAtScope
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDeleteAtScope func(ctx context.Context, scope string, options *armresources.TagsClientBeginDeleteAtScopeOptions) (resp azfake.PollerResponder[armresources.TagsClientDeleteAtScopeResponse], errResp azfake.ErrorResponder)

	// DeleteValue is the fake for method TagsClient.DeleteValue
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	DeleteValue func(ctx context.Context, tagName string, tagValue string, options *armresources.TagsClientDeleteValueOptions) (resp azfake.Responder[armresources.TagsClientDeleteValueResponse], errResp azfake.ErrorResponder)

	// GetAtScope is the fake for method TagsClient.GetAtScope
	// HTTP status codes to indicate success: http.StatusOK
	GetAtScope func(ctx context.Context, scope string, options *armresources.TagsClientGetAtScopeOptions) (resp azfake.Responder[armresources.TagsClientGetAtScopeResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method TagsClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(options *armresources.TagsClientListOptions) (resp azfake.PagerResponder[armresources.TagsClientListResponse])

	// BeginUpdateAtScope is the fake for method TagsClient.BeginUpdateAtScope
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginUpdateAtScope func(ctx context.Context, scope string, parameters armresources.TagsPatchResource, options *armresources.TagsClientBeginUpdateAtScopeOptions) (resp azfake.PollerResponder[armresources.TagsClientUpdateAtScopeResponse], errResp azfake.ErrorResponder)
}

// NewTagsServerTransport creates a new instance of TagsServerTransport with the provided implementation.
// The returned TagsServerTransport instance is connected to an instance of armresources.TagsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewTagsServerTransport(srv *TagsServer) *TagsServerTransport {
	return &TagsServerTransport{
		srv:                        srv,
		beginCreateOrUpdateAtScope: newTracker[azfake.PollerResponder[armresources.TagsClientCreateOrUpdateAtScopeResponse]](),
		beginDeleteAtScope:         newTracker[azfake.PollerResponder[armresources.TagsClientDeleteAtScopeResponse]](),
		newListPager:               newTracker[azfake.PagerResponder[armresources.TagsClientListResponse]](),
		beginUpdateAtScope:         newTracker[azfake.PollerResponder[armresources.TagsClientUpdateAtScopeResponse]](),
	}
}

// TagsServerTransport connects instances of armresources.TagsClient to instances of TagsServer.
// Don't use this type directly, use NewTagsServerTransport instead.
type TagsServerTransport struct {
	srv                        *TagsServer
	beginCreateOrUpdateAtScope *tracker[azfake.PollerResponder[armresources.TagsClientCreateOrUpdateAtScopeResponse]]
	beginDeleteAtScope         *tracker[azfake.PollerResponder[armresources.TagsClientDeleteAtScopeResponse]]
	newListPager               *tracker[azfake.PagerResponder[armresources.TagsClientListResponse]]
	beginUpdateAtScope         *tracker[azfake.PollerResponder[armresources.TagsClientUpdateAtScopeResponse]]
}

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

func (t *TagsServerTransport) 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 tagsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = tagsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "TagsClient.CreateOrUpdate":
				res.resp, res.err = t.dispatchCreateOrUpdate(req)
			case "TagsClient.BeginCreateOrUpdateAtScope":
				res.resp, res.err = t.dispatchBeginCreateOrUpdateAtScope(req)
			case "TagsClient.CreateOrUpdateValue":
				res.resp, res.err = t.dispatchCreateOrUpdateValue(req)
			case "TagsClient.Delete":
				res.resp, res.err = t.dispatchDelete(req)
			case "TagsClient.BeginDeleteAtScope":
				res.resp, res.err = t.dispatchBeginDeleteAtScope(req)
			case "TagsClient.DeleteValue":
				res.resp, res.err = t.dispatchDeleteValue(req)
			case "TagsClient.GetAtScope":
				res.resp, res.err = t.dispatchGetAtScope(req)
			case "TagsClient.NewListPager":
				res.resp, res.err = t.dispatchNewListPager(req)
			case "TagsClient.BeginUpdateAtScope":
				res.resp, res.err = t.dispatchBeginUpdateAtScope(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 (t *TagsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if t.srv.CreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tagNames/(?P<tagName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 2 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	tagNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("tagName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.CreateOrUpdate(req.Context(), tagNameParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).TagDetails, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (t *TagsServerTransport) dispatchBeginCreateOrUpdateAtScope(req *http.Request) (*http.Response, error) {
	if t.srv.BeginCreateOrUpdateAtScope == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdateAtScope not implemented")}
	}
	beginCreateOrUpdateAtScope := t.beginCreateOrUpdateAtScope.get(req)
	if beginCreateOrUpdateAtScope == nil {
		const regexStr = `/(?P<scope>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Resources/tags/default`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 1 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		body, err := server.UnmarshalRequestAsJSON[armresources.TagsResource](req)
		if err != nil {
			return nil, err
		}
		scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := t.srv.BeginCreateOrUpdateAtScope(req.Context(), scopeParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateOrUpdateAtScope = &respr
		t.beginCreateOrUpdateAtScope.add(req, beginCreateOrUpdateAtScope)
	}

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

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

	return resp, nil
}

func (t *TagsServerTransport) dispatchCreateOrUpdateValue(req *http.Request) (*http.Response, error) {
	if t.srv.CreateOrUpdateValue == nil {
		return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdateValue not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tagNames/(?P<tagName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tagValues/(?P<tagValue>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 3 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	tagNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("tagName")])
	if err != nil {
		return nil, err
	}
	tagValueParam, err := url.PathUnescape(matches[regex.SubexpIndex("tagValue")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.CreateOrUpdateValue(req.Context(), tagNameParam, tagValueParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).TagValue, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (t *TagsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if t.srv.Delete == nil {
		return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tagNames/(?P<tagName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 2 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	tagNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("tagName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.Delete(req.Context(), tagNameParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)}
	}
	resp, err := server.NewResponse(respContent, req, nil)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (t *TagsServerTransport) dispatchBeginDeleteAtScope(req *http.Request) (*http.Response, error) {
	if t.srv.BeginDeleteAtScope == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDeleteAtScope not implemented")}
	}
	beginDeleteAtScope := t.beginDeleteAtScope.get(req)
	if beginDeleteAtScope == nil {
		const regexStr = `/(?P<scope>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Resources/tags/default`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 1 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := t.srv.BeginDeleteAtScope(req.Context(), scopeParam, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDeleteAtScope = &respr
		t.beginDeleteAtScope.add(req, beginDeleteAtScope)
	}

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

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

	return resp, nil
}

func (t *TagsServerTransport) dispatchDeleteValue(req *http.Request) (*http.Response, error) {
	if t.srv.DeleteValue == nil {
		return nil, &nonRetriableError{errors.New("fake for method DeleteValue not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tagNames/(?P<tagName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tagValues/(?P<tagValue>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 3 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	tagNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("tagName")])
	if err != nil {
		return nil, err
	}
	tagValueParam, err := url.PathUnescape(matches[regex.SubexpIndex("tagValue")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.DeleteValue(req.Context(), tagNameParam, tagValueParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)}
	}
	resp, err := server.NewResponse(respContent, req, nil)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (t *TagsServerTransport) dispatchGetAtScope(req *http.Request) (*http.Response, error) {
	if t.srv.GetAtScope == nil {
		return nil, &nonRetriableError{errors.New("fake for method GetAtScope not implemented")}
	}
	const regexStr = `/(?P<scope>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Resources/tags/default`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 1 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.GetAtScope(req.Context(), scopeParam, 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).TagsResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (t *TagsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if t.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := t.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tagNames`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 1 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		resp := t.srv.NewListPager(nil)
		newListPager = &resp
		t.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armresources.TagsClientListResponse, 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) {
		t.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		t.newListPager.remove(req)
	}
	return resp, nil
}

func (t *TagsServerTransport) dispatchBeginUpdateAtScope(req *http.Request) (*http.Response, error) {
	if t.srv.BeginUpdateAtScope == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginUpdateAtScope not implemented")}
	}
	beginUpdateAtScope := t.beginUpdateAtScope.get(req)
	if beginUpdateAtScope == nil {
		const regexStr = `/(?P<scope>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Resources/tags/default`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 1 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		body, err := server.UnmarshalRequestAsJSON[armresources.TagsPatchResource](req)
		if err != nil {
			return nil, err
		}
		scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := t.srv.BeginUpdateAtScope(req.Context(), scopeParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginUpdateAtScope = &respr
		t.beginUpdateAtScope.add(req, beginUpdateAtScope)
	}

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

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

	return resp, nil
}

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