// 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/dns/armdns"
	"net/http"
	"net/url"
	"regexp"
	"slices"
	"strconv"
)

// ZonesServer is a fake server for instances of the armdns.ZonesClient type.
type ZonesServer struct {
	// CreateOrUpdate is the fake for method ZonesClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrUpdate func(ctx context.Context, resourceGroupName string, zoneName string, parameters armdns.Zone, options *armdns.ZonesClientCreateOrUpdateOptions) (resp azfake.Responder[armdns.ZonesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method ZonesClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, zoneName string, options *armdns.ZonesClientBeginDeleteOptions) (resp azfake.PollerResponder[armdns.ZonesClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method ZonesClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, zoneName string, options *armdns.ZonesClientGetOptions) (resp azfake.Responder[armdns.ZonesClientGetResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method ZonesClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(options *armdns.ZonesClientListOptions) (resp azfake.PagerResponder[armdns.ZonesClientListResponse])

	// NewListByResourceGroupPager is the fake for method ZonesClient.NewListByResourceGroupPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByResourceGroupPager func(resourceGroupName string, options *armdns.ZonesClientListByResourceGroupOptions) (resp azfake.PagerResponder[armdns.ZonesClientListByResourceGroupResponse])

	// Update is the fake for method ZonesClient.Update
	// HTTP status codes to indicate success: http.StatusOK
	Update func(ctx context.Context, resourceGroupName string, zoneName string, parameters armdns.ZoneUpdate, options *armdns.ZonesClientUpdateOptions) (resp azfake.Responder[armdns.ZonesClientUpdateResponse], errResp azfake.ErrorResponder)
}

// NewZonesServerTransport creates a new instance of ZonesServerTransport with the provided implementation.
// The returned ZonesServerTransport instance is connected to an instance of armdns.ZonesClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewZonesServerTransport(srv *ZonesServer) *ZonesServerTransport {
	return &ZonesServerTransport{
		srv:                         srv,
		beginDelete:                 newTracker[azfake.PollerResponder[armdns.ZonesClientDeleteResponse]](),
		newListPager:                newTracker[azfake.PagerResponder[armdns.ZonesClientListResponse]](),
		newListByResourceGroupPager: newTracker[azfake.PagerResponder[armdns.ZonesClientListByResourceGroupResponse]](),
	}
}

// ZonesServerTransport connects instances of armdns.ZonesClient to instances of ZonesServer.
// Don't use this type directly, use NewZonesServerTransport instead.
type ZonesServerTransport struct {
	srv                         *ZonesServer
	beginDelete                 *tracker[azfake.PollerResponder[armdns.ZonesClientDeleteResponse]]
	newListPager                *tracker[azfake.PagerResponder[armdns.ZonesClientListResponse]]
	newListByResourceGroupPager *tracker[azfake.PagerResponder[armdns.ZonesClientListByResourceGroupResponse]]
}

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

func (z *ZonesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if zonesServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = zonesServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "ZonesClient.CreateOrUpdate":
				res.resp, res.err = z.dispatchCreateOrUpdate(req)
			case "ZonesClient.BeginDelete":
				res.resp, res.err = z.dispatchBeginDelete(req)
			case "ZonesClient.Get":
				res.resp, res.err = z.dispatchGet(req)
			case "ZonesClient.NewListPager":
				res.resp, res.err = z.dispatchNewListPager(req)
			case "ZonesClient.NewListByResourceGroupPager":
				res.resp, res.err = z.dispatchNewListByResourceGroupPager(req)
			case "ZonesClient.Update":
				res.resp, res.err = z.dispatchUpdate(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 (z *ZonesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if z.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/dnsZones/(?P<zoneName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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)
	}
	body, err := server.UnmarshalRequestAsJSON[armdns.Zone](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	zoneNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("zoneName")])
	if err != nil {
		return nil, err
	}
	ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
	ifNoneMatchParam := getOptional(getHeaderValue(req.Header, "If-None-Match"))
	var options *armdns.ZonesClientCreateOrUpdateOptions
	if ifMatchParam != nil || ifNoneMatchParam != nil {
		options = &armdns.ZonesClientCreateOrUpdateOptions{
			IfMatch:     ifMatchParam,
			IfNoneMatch: ifNoneMatchParam,
		}
	}
	respr, errRespr := z.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, zoneNameParam, body, options)
	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).Zone, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (z *ZonesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if z.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := z.beginDelete.get(req)
	if beginDelete == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Network/dnsZones/(?P<zoneName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		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
		}
		zoneNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("zoneName")])
		if err != nil {
			return nil, err
		}
		ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
		var options *armdns.ZonesClientBeginDeleteOptions
		if ifMatchParam != nil {
			options = &armdns.ZonesClientBeginDeleteOptions{
				IfMatch: ifMatchParam,
			}
		}
		respr, errRespr := z.srv.BeginDelete(req.Context(), resourceGroupNameParam, zoneNameParam, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		z.beginDelete.add(req, beginDelete)
	}

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

	if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) {
		z.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) {
		z.beginDelete.remove(req)
	}

	return resp, nil
}

func (z *ZonesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if z.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/dnsZones/(?P<zoneName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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
	}
	zoneNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("zoneName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := z.srv.Get(req.Context(), resourceGroupNameParam, zoneNameParam, 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).Zone, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (z *ZonesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if z.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := z.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Network/dnszones`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 2 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		qp := req.URL.Query()
		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
		}
		var options *armdns.ZonesClientListOptions
		if topParam != nil {
			options = &armdns.ZonesClientListOptions{
				Top: topParam,
			}
		}
		resp := z.srv.NewListPager(options)
		newListPager = &resp
		z.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armdns.ZonesClientListResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		z.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		z.newListPager.remove(req)
	}
	return resp, nil
}

func (z *ZonesServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) {
	if z.srv.NewListByResourceGroupPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")}
	}
	newListByResourceGroupPager := z.newListByResourceGroupPager.get(req)
	if newListByResourceGroupPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Network/dnsZones`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if 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
		}
		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
		}
		var options *armdns.ZonesClientListByResourceGroupOptions
		if topParam != nil {
			options = &armdns.ZonesClientListByResourceGroupOptions{
				Top: topParam,
			}
		}
		resp := z.srv.NewListByResourceGroupPager(resourceGroupNameParam, options)
		newListByResourceGroupPager = &resp
		z.newListByResourceGroupPager.add(req, newListByResourceGroupPager)
		server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armdns.ZonesClientListByResourceGroupResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByResourceGroupPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		z.newListByResourceGroupPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByResourceGroupPager) {
		z.newListByResourceGroupPager.remove(req)
	}
	return resp, nil
}

func (z *ZonesServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) {
	if z.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/dnsZones/(?P<zoneName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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)
	}
	body, err := server.UnmarshalRequestAsJSON[armdns.ZoneUpdate](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	zoneNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("zoneName")])
	if err != nil {
		return nil, err
	}
	ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
	var options *armdns.ZonesClientUpdateOptions
	if ifMatchParam != nil {
		options = &armdns.ZonesClientUpdateOptions{
			IfMatch: ifMatchParam,
		}
	}
	respr, errRespr := z.srv.Update(req.Context(), resourceGroupNameParam, zoneNameParam, body, options)
	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).Zone, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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