// 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/apimanagement/armapimanagement/v4"
	"net/http"
	"net/url"
	"regexp"
	"slices"
	"strconv"
)

// TagOperationLinkServer is a fake server for instances of the armapimanagement.TagOperationLinkClient type.
type TagOperationLinkServer struct {
	// CreateOrUpdate is the fake for method TagOperationLinkClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrUpdate func(ctx context.Context, resourceGroupName string, serviceName string, tagID string, operationLinkID string, parameters armapimanagement.TagOperationLinkContract, options *armapimanagement.TagOperationLinkClientCreateOrUpdateOptions) (resp azfake.Responder[armapimanagement.TagOperationLinkClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method TagOperationLinkClient.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, resourceGroupName string, serviceName string, tagID string, operationLinkID string, options *armapimanagement.TagOperationLinkClientDeleteOptions) (resp azfake.Responder[armapimanagement.TagOperationLinkClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method TagOperationLinkClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, serviceName string, tagID string, operationLinkID string, options *armapimanagement.TagOperationLinkClientGetOptions) (resp azfake.Responder[armapimanagement.TagOperationLinkClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByProductPager is the fake for method TagOperationLinkClient.NewListByProductPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByProductPager func(resourceGroupName string, serviceName string, tagID string, options *armapimanagement.TagOperationLinkClientListByProductOptions) (resp azfake.PagerResponder[armapimanagement.TagOperationLinkClientListByProductResponse])
}

// NewTagOperationLinkServerTransport creates a new instance of TagOperationLinkServerTransport with the provided implementation.
// The returned TagOperationLinkServerTransport instance is connected to an instance of armapimanagement.TagOperationLinkClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewTagOperationLinkServerTransport(srv *TagOperationLinkServer) *TagOperationLinkServerTransport {
	return &TagOperationLinkServerTransport{
		srv:                   srv,
		newListByProductPager: newTracker[azfake.PagerResponder[armapimanagement.TagOperationLinkClientListByProductResponse]](),
	}
}

// TagOperationLinkServerTransport connects instances of armapimanagement.TagOperationLinkClient to instances of TagOperationLinkServer.
// Don't use this type directly, use NewTagOperationLinkServerTransport instead.
type TagOperationLinkServerTransport struct {
	srv                   *TagOperationLinkServer
	newListByProductPager *tracker[azfake.PagerResponder[armapimanagement.TagOperationLinkClientListByProductResponse]]
}

// Do implements the policy.Transporter interface for TagOperationLinkServerTransport.
func (t *TagOperationLinkServerTransport) 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 *TagOperationLinkServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if tagOperationLinkServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = tagOperationLinkServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "TagOperationLinkClient.CreateOrUpdate":
				res.resp, res.err = t.dispatchCreateOrUpdate(req)
			case "TagOperationLinkClient.Delete":
				res.resp, res.err = t.dispatchDelete(req)
			case "TagOperationLinkClient.Get":
				res.resp, res.err = t.dispatchGet(req)
			case "TagOperationLinkClient.NewListByProductPager":
				res.resp, res.err = t.dispatchNewListByProductPager(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 (t *TagOperationLinkServerTransport) 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~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiManagement/service/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tags/(?P<tagId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/operationLinks/(?P<operationLinkId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armapimanagement.TagOperationLinkContract](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
	if err != nil {
		return nil, err
	}
	tagIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("tagId")])
	if err != nil {
		return nil, err
	}
	operationLinkIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("operationLinkId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, serviceNameParam, tagIDParam, operationLinkIDParam, body, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !slices.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).TagOperationLinkContract, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (t *TagOperationLinkServerTransport) 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~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiManagement/service/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tags/(?P<tagId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/operationLinks/(?P<operationLinkId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		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
	}
	serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
	if err != nil {
		return nil, err
	}
	tagIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("tagId")])
	if err != nil {
		return nil, err
	}
	operationLinkIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("operationLinkId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.Delete(req.Context(), resourceGroupNameParam, serviceNameParam, tagIDParam, operationLinkIDParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !slices.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 *TagOperationLinkServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if t.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\.ApiManagement/service/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tags/(?P<tagId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/operationLinks/(?P<operationLinkId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		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
	}
	serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
	if err != nil {
		return nil, err
	}
	tagIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("tagId")])
	if err != nil {
		return nil, err
	}
	operationLinkIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("operationLinkId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.Get(req.Context(), resourceGroupNameParam, serviceNameParam, tagIDParam, operationLinkIDParam, 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).TagOperationLinkContract, req)
	if err != nil {
		return nil, err
	}
	if val := server.GetResponse(respr).ETag; val != nil {
		resp.Header.Set("ETag", *val)
	}
	return resp, nil
}

func (t *TagOperationLinkServerTransport) dispatchNewListByProductPager(req *http.Request) (*http.Response, error) {
	if t.srv.NewListByProductPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByProductPager not implemented")}
	}
	newListByProductPager := t.newListByProductPager.get(req)
	if newListByProductPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiManagement/service/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tags/(?P<tagId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/operationLinks`
		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
		}
		serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
		if err != nil {
			return nil, err
		}
		tagIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("tagId")])
		if err != nil {
			return nil, err
		}
		filterParam := getOptional(qp.Get("$filter"))
		topParam, err := parseOptional(qp.Get("$top"), func(v string) (int32, error) {
			p, parseErr := strconv.ParseInt(v, 10, 32)
			if parseErr != nil {
				return 0, parseErr
			}
			return int32(p), nil
		})
		if err != nil {
			return nil, err
		}
		skipParam, err := parseOptional(qp.Get("$skip"), func(v string) (int32, error) {
			p, parseErr := strconv.ParseInt(v, 10, 32)
			if parseErr != nil {
				return 0, parseErr
			}
			return int32(p), nil
		})
		if err != nil {
			return nil, err
		}
		var options *armapimanagement.TagOperationLinkClientListByProductOptions
		if filterParam != nil || topParam != nil || skipParam != nil {
			options = &armapimanagement.TagOperationLinkClientListByProductOptions{
				Filter: filterParam,
				Top:    topParam,
				Skip:   skipParam,
			}
		}
		resp := t.srv.NewListByProductPager(resourceGroupNameParam, serviceNameParam, tagIDParam, options)
		newListByProductPager = &resp
		t.newListByProductPager.add(req, newListByProductPager)
		server.PagerResponderInjectNextLinks(newListByProductPager, req, func(page *armapimanagement.TagOperationLinkClientListByProductResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByProductPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		t.newListByProductPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByProductPager) {
		t.newListByProductPager.remove(req)
	}
	return resp, nil
}

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