// 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/sqlvirtualmachine/armsqlvirtualmachine"
	"net/http"
	"net/url"
	"regexp"
	"slices"
)

// AvailabilityGroupListenersServer is a fake server for instances of the armsqlvirtualmachine.AvailabilityGroupListenersClient type.
type AvailabilityGroupListenersServer struct {
	// BeginCreateOrUpdate is the fake for method AvailabilityGroupListenersClient.BeginCreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, sqlVirtualMachineGroupName string, availabilityGroupListenerName string, parameters armsqlvirtualmachine.AvailabilityGroupListener, options *armsqlvirtualmachine.AvailabilityGroupListenersClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armsqlvirtualmachine.AvailabilityGroupListenersClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method AvailabilityGroupListenersClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, sqlVirtualMachineGroupName string, availabilityGroupListenerName string, options *armsqlvirtualmachine.AvailabilityGroupListenersClientBeginDeleteOptions) (resp azfake.PollerResponder[armsqlvirtualmachine.AvailabilityGroupListenersClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method AvailabilityGroupListenersClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, sqlVirtualMachineGroupName string, availabilityGroupListenerName string, options *armsqlvirtualmachine.AvailabilityGroupListenersClientGetOptions) (resp azfake.Responder[armsqlvirtualmachine.AvailabilityGroupListenersClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByGroupPager is the fake for method AvailabilityGroupListenersClient.NewListByGroupPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByGroupPager func(resourceGroupName string, sqlVirtualMachineGroupName string, options *armsqlvirtualmachine.AvailabilityGroupListenersClientListByGroupOptions) (resp azfake.PagerResponder[armsqlvirtualmachine.AvailabilityGroupListenersClientListByGroupResponse])
}

// NewAvailabilityGroupListenersServerTransport creates a new instance of AvailabilityGroupListenersServerTransport with the provided implementation.
// The returned AvailabilityGroupListenersServerTransport instance is connected to an instance of armsqlvirtualmachine.AvailabilityGroupListenersClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewAvailabilityGroupListenersServerTransport(srv *AvailabilityGroupListenersServer) *AvailabilityGroupListenersServerTransport {
	return &AvailabilityGroupListenersServerTransport{
		srv:                 srv,
		beginCreateOrUpdate: newTracker[azfake.PollerResponder[armsqlvirtualmachine.AvailabilityGroupListenersClientCreateOrUpdateResponse]](),
		beginDelete:         newTracker[azfake.PollerResponder[armsqlvirtualmachine.AvailabilityGroupListenersClientDeleteResponse]](),
		newListByGroupPager: newTracker[azfake.PagerResponder[armsqlvirtualmachine.AvailabilityGroupListenersClientListByGroupResponse]](),
	}
}

// AvailabilityGroupListenersServerTransport connects instances of armsqlvirtualmachine.AvailabilityGroupListenersClient to instances of AvailabilityGroupListenersServer.
// Don't use this type directly, use NewAvailabilityGroupListenersServerTransport instead.
type AvailabilityGroupListenersServerTransport struct {
	srv                 *AvailabilityGroupListenersServer
	beginCreateOrUpdate *tracker[azfake.PollerResponder[armsqlvirtualmachine.AvailabilityGroupListenersClientCreateOrUpdateResponse]]
	beginDelete         *tracker[azfake.PollerResponder[armsqlvirtualmachine.AvailabilityGroupListenersClientDeleteResponse]]
	newListByGroupPager *tracker[azfake.PagerResponder[armsqlvirtualmachine.AvailabilityGroupListenersClientListByGroupResponse]]
}

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

func (a *AvailabilityGroupListenersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if availabilityGroupListenersServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = availabilityGroupListenersServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "AvailabilityGroupListenersClient.BeginCreateOrUpdate":
				res.resp, res.err = a.dispatchBeginCreateOrUpdate(req)
			case "AvailabilityGroupListenersClient.BeginDelete":
				res.resp, res.err = a.dispatchBeginDelete(req)
			case "AvailabilityGroupListenersClient.Get":
				res.resp, res.err = a.dispatchGet(req)
			case "AvailabilityGroupListenersClient.NewListByGroupPager":
				res.resp, res.err = a.dispatchNewListByGroupPager(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 (a *AvailabilityGroupListenersServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if a.srv.BeginCreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")}
	}
	beginCreateOrUpdate := a.beginCreateOrUpdate.get(req)
	if beginCreateOrUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.SqlVirtualMachine/sqlVirtualMachineGroups/(?P<sqlVirtualMachineGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/availabilityGroupListeners/(?P<availabilityGroupListenerName>[!#&$-;=?-\[\]_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[armsqlvirtualmachine.AvailabilityGroupListener](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		sqlVirtualMachineGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("sqlVirtualMachineGroupName")])
		if err != nil {
			return nil, err
		}
		availabilityGroupListenerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("availabilityGroupListenerName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := a.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, sqlVirtualMachineGroupNameParam, availabilityGroupListenerNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateOrUpdate = &respr
		a.beginCreateOrUpdate.add(req, beginCreateOrUpdate)
	}

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

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

	return resp, nil
}

func (a *AvailabilityGroupListenersServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if a.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := a.beginDelete.get(req)
	if beginDelete == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.SqlVirtualMachine/sqlVirtualMachineGroups/(?P<sqlVirtualMachineGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/availabilityGroupListeners/(?P<availabilityGroupListenerName>[!#&$-;=?-\[\]_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
		}
		sqlVirtualMachineGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("sqlVirtualMachineGroupName")])
		if err != nil {
			return nil, err
		}
		availabilityGroupListenerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("availabilityGroupListenerName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := a.srv.BeginDelete(req.Context(), resourceGroupNameParam, sqlVirtualMachineGroupNameParam, availabilityGroupListenerNameParam, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		a.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) {
		a.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) {
		a.beginDelete.remove(req)
	}

	return resp, nil
}

func (a *AvailabilityGroupListenersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if a.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\.SqlVirtualMachine/sqlVirtualMachineGroups/(?P<sqlVirtualMachineGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/availabilityGroupListeners/(?P<availabilityGroupListenerName>[!#&$-;=?-\[\]_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
	}
	sqlVirtualMachineGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("sqlVirtualMachineGroupName")])
	if err != nil {
		return nil, err
	}
	availabilityGroupListenerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("availabilityGroupListenerName")])
	if err != nil {
		return nil, err
	}
	expandParam := getOptional(qp.Get("$expand"))
	var options *armsqlvirtualmachine.AvailabilityGroupListenersClientGetOptions
	if expandParam != nil {
		options = &armsqlvirtualmachine.AvailabilityGroupListenersClientGetOptions{
			Expand: expandParam,
		}
	}
	respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, sqlVirtualMachineGroupNameParam, availabilityGroupListenerNameParam, 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).AvailabilityGroupListener, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *AvailabilityGroupListenersServerTransport) dispatchNewListByGroupPager(req *http.Request) (*http.Response, error) {
	if a.srv.NewListByGroupPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByGroupPager not implemented")}
	}
	newListByGroupPager := a.newListByGroupPager.get(req)
	if newListByGroupPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.SqlVirtualMachine/sqlVirtualMachineGroups/(?P<sqlVirtualMachineGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/availabilityGroupListeners`
		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
		}
		sqlVirtualMachineGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("sqlVirtualMachineGroupName")])
		if err != nil {
			return nil, err
		}
		resp := a.srv.NewListByGroupPager(resourceGroupNameParam, sqlVirtualMachineGroupNameParam, nil)
		newListByGroupPager = &resp
		a.newListByGroupPager.add(req, newListByGroupPager)
		server.PagerResponderInjectNextLinks(newListByGroupPager, req, func(page *armsqlvirtualmachine.AvailabilityGroupListenersClientListByGroupResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByGroupPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		a.newListByGroupPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByGroupPager) {
		a.newListByGroupPager.remove(req)
	}
	return resp, nil
}

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