// 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/dnsresolver/armdnsresolver"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
)

// ForwardingRulesServer is a fake server for instances of the armdnsresolver.ForwardingRulesClient type.
type ForwardingRulesServer struct {
	// CreateOrUpdate is the fake for method ForwardingRulesClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrUpdate func(ctx context.Context, resourceGroupName string, dnsForwardingRulesetName string, forwardingRuleName string, parameters armdnsresolver.ForwardingRule, options *armdnsresolver.ForwardingRulesClientCreateOrUpdateOptions) (resp azfake.Responder[armdnsresolver.ForwardingRulesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method ForwardingRulesClient.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, resourceGroupName string, dnsForwardingRulesetName string, forwardingRuleName string, options *armdnsresolver.ForwardingRulesClientDeleteOptions) (resp azfake.Responder[armdnsresolver.ForwardingRulesClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method ForwardingRulesClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, dnsForwardingRulesetName string, forwardingRuleName string, options *armdnsresolver.ForwardingRulesClientGetOptions) (resp azfake.Responder[armdnsresolver.ForwardingRulesClientGetResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method ForwardingRulesClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(resourceGroupName string, dnsForwardingRulesetName string, options *armdnsresolver.ForwardingRulesClientListOptions) (resp azfake.PagerResponder[armdnsresolver.ForwardingRulesClientListResponse])

	// Update is the fake for method ForwardingRulesClient.Update
	// HTTP status codes to indicate success: http.StatusOK
	Update func(ctx context.Context, resourceGroupName string, dnsForwardingRulesetName string, forwardingRuleName string, parameters armdnsresolver.ForwardingRulePatch, options *armdnsresolver.ForwardingRulesClientUpdateOptions) (resp azfake.Responder[armdnsresolver.ForwardingRulesClientUpdateResponse], errResp azfake.ErrorResponder)
}

// NewForwardingRulesServerTransport creates a new instance of ForwardingRulesServerTransport with the provided implementation.
// The returned ForwardingRulesServerTransport instance is connected to an instance of armdnsresolver.ForwardingRulesClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewForwardingRulesServerTransport(srv *ForwardingRulesServer) *ForwardingRulesServerTransport {
	return &ForwardingRulesServerTransport{
		srv:          srv,
		newListPager: newTracker[azfake.PagerResponder[armdnsresolver.ForwardingRulesClientListResponse]](),
	}
}

// ForwardingRulesServerTransport connects instances of armdnsresolver.ForwardingRulesClient to instances of ForwardingRulesServer.
// Don't use this type directly, use NewForwardingRulesServerTransport instead.
type ForwardingRulesServerTransport struct {
	srv          *ForwardingRulesServer
	newListPager *tracker[azfake.PagerResponder[armdnsresolver.ForwardingRulesClientListResponse]]
}

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

func (f *ForwardingRulesServerTransport) 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 forwardingRulesServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = forwardingRulesServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "ForwardingRulesClient.CreateOrUpdate":
				res.resp, res.err = f.dispatchCreateOrUpdate(req)
			case "ForwardingRulesClient.Delete":
				res.resp, res.err = f.dispatchDelete(req)
			case "ForwardingRulesClient.Get":
				res.resp, res.err = f.dispatchGet(req)
			case "ForwardingRulesClient.NewListPager":
				res.resp, res.err = f.dispatchNewListPager(req)
			case "ForwardingRulesClient.Update":
				res.resp, res.err = f.dispatchUpdate(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 (f *ForwardingRulesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if f.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\.Network/dnsForwardingRulesets/(?P<dnsForwardingRulesetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/forwardingRules/(?P<forwardingRuleName>[!#&$-;=?-\[\]_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[armdnsresolver.ForwardingRule](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	dnsForwardingRulesetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsForwardingRulesetName")])
	if err != nil {
		return nil, err
	}
	forwardingRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("forwardingRuleName")])
	if err != nil {
		return nil, err
	}
	ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
	ifNoneMatchParam := getOptional(getHeaderValue(req.Header, "If-None-Match"))
	var options *armdnsresolver.ForwardingRulesClientCreateOrUpdateOptions
	if ifMatchParam != nil || ifNoneMatchParam != nil {
		options = &armdnsresolver.ForwardingRulesClientCreateOrUpdateOptions{
			IfMatch:     ifMatchParam,
			IfNoneMatch: ifNoneMatchParam,
		}
	}
	respr, errRespr := f.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, dnsForwardingRulesetNameParam, forwardingRuleNameParam, body, options)
	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).ForwardingRule, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (f *ForwardingRulesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if f.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\.Network/dnsForwardingRulesets/(?P<dnsForwardingRulesetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/forwardingRules/(?P<forwardingRuleName>[!#&$-;=?-\[\]_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
	}
	dnsForwardingRulesetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsForwardingRulesetName")])
	if err != nil {
		return nil, err
	}
	forwardingRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("forwardingRuleName")])
	if err != nil {
		return nil, err
	}
	ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
	var options *armdnsresolver.ForwardingRulesClientDeleteOptions
	if ifMatchParam != nil {
		options = &armdnsresolver.ForwardingRulesClientDeleteOptions{
			IfMatch: ifMatchParam,
		}
	}
	respr, errRespr := f.srv.Delete(req.Context(), resourceGroupNameParam, dnsForwardingRulesetNameParam, forwardingRuleNameParam, options)
	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 (f *ForwardingRulesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if f.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\.Network/dnsForwardingRulesets/(?P<dnsForwardingRulesetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/forwardingRules/(?P<forwardingRuleName>[!#&$-;=?-\[\]_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
	}
	dnsForwardingRulesetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsForwardingRulesetName")])
	if err != nil {
		return nil, err
	}
	forwardingRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("forwardingRuleName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := f.srv.Get(req.Context(), resourceGroupNameParam, dnsForwardingRulesetNameParam, forwardingRuleNameParam, 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).ForwardingRule, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (f *ForwardingRulesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if f.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := f.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Network/dnsForwardingRulesets/(?P<dnsForwardingRulesetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/forwardingRules`
		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)
		}
		qp := req.URL.Query()
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		dnsForwardingRulesetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsForwardingRulesetName")])
		if err != nil {
			return nil, err
		}
		topUnescaped, err := url.QueryUnescape(qp.Get("$top"))
		if err != nil {
			return nil, err
		}
		topParam, err := parseOptional(topUnescaped, 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 *armdnsresolver.ForwardingRulesClientListOptions
		if topParam != nil {
			options = &armdnsresolver.ForwardingRulesClientListOptions{
				Top: topParam,
			}
		}
		resp := f.srv.NewListPager(resourceGroupNameParam, dnsForwardingRulesetNameParam, options)
		newListPager = &resp
		f.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armdnsresolver.ForwardingRulesClientListResponse, 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) {
		f.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		f.newListPager.remove(req)
	}
	return resp, nil
}

func (f *ForwardingRulesServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) {
	if f.srv.Update == nil {
		return nil, &nonRetriableError{errors.New("fake for method Update not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Network/dnsForwardingRulesets/(?P<dnsForwardingRulesetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/forwardingRules/(?P<forwardingRuleName>[!#&$-;=?-\[\]_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[armdnsresolver.ForwardingRulePatch](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	dnsForwardingRulesetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsForwardingRulesetName")])
	if err != nil {
		return nil, err
	}
	forwardingRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("forwardingRuleName")])
	if err != nil {
		return nil, err
	}
	ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
	var options *armdnsresolver.ForwardingRulesClientUpdateOptions
	if ifMatchParam != nil {
		options = &armdnsresolver.ForwardingRulesClientUpdateOptions{
			IfMatch: ifMatchParam,
		}
	}
	respr, errRespr := f.srv.Update(req.Context(), resourceGroupNameParam, dnsForwardingRulesetNameParam, forwardingRuleNameParam, body, options)
	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).ForwardingRule, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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