// 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/sql/armsql/v2"
	"net/http"
	"net/url"
	"regexp"
)

// SyncAgentsServer is a fake server for instances of the armsql.SyncAgentsClient type.
type SyncAgentsServer struct {
	// BeginCreateOrUpdate is the fake for method SyncAgentsClient.BeginCreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated, http.StatusAccepted
	BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, serverName string, syncAgentName string, parameters armsql.SyncAgent, options *armsql.SyncAgentsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armsql.SyncAgentsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method SyncAgentsClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, serverName string, syncAgentName string, options *armsql.SyncAgentsClientBeginDeleteOptions) (resp azfake.PollerResponder[armsql.SyncAgentsClientDeleteResponse], errResp azfake.ErrorResponder)

	// GenerateKey is the fake for method SyncAgentsClient.GenerateKey
	// HTTP status codes to indicate success: http.StatusOK
	GenerateKey func(ctx context.Context, resourceGroupName string, serverName string, syncAgentName string, options *armsql.SyncAgentsClientGenerateKeyOptions) (resp azfake.Responder[armsql.SyncAgentsClientGenerateKeyResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method SyncAgentsClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, serverName string, syncAgentName string, options *armsql.SyncAgentsClientGetOptions) (resp azfake.Responder[armsql.SyncAgentsClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByServerPager is the fake for method SyncAgentsClient.NewListByServerPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByServerPager func(resourceGroupName string, serverName string, options *armsql.SyncAgentsClientListByServerOptions) (resp azfake.PagerResponder[armsql.SyncAgentsClientListByServerResponse])

	// NewListLinkedDatabasesPager is the fake for method SyncAgentsClient.NewListLinkedDatabasesPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListLinkedDatabasesPager func(resourceGroupName string, serverName string, syncAgentName string, options *armsql.SyncAgentsClientListLinkedDatabasesOptions) (resp azfake.PagerResponder[armsql.SyncAgentsClientListLinkedDatabasesResponse])
}

// NewSyncAgentsServerTransport creates a new instance of SyncAgentsServerTransport with the provided implementation.
// The returned SyncAgentsServerTransport instance is connected to an instance of armsql.SyncAgentsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewSyncAgentsServerTransport(srv *SyncAgentsServer) *SyncAgentsServerTransport {
	return &SyncAgentsServerTransport{
		srv:                         srv,
		beginCreateOrUpdate:         newTracker[azfake.PollerResponder[armsql.SyncAgentsClientCreateOrUpdateResponse]](),
		beginDelete:                 newTracker[azfake.PollerResponder[armsql.SyncAgentsClientDeleteResponse]](),
		newListByServerPager:        newTracker[azfake.PagerResponder[armsql.SyncAgentsClientListByServerResponse]](),
		newListLinkedDatabasesPager: newTracker[azfake.PagerResponder[armsql.SyncAgentsClientListLinkedDatabasesResponse]](),
	}
}

// SyncAgentsServerTransport connects instances of armsql.SyncAgentsClient to instances of SyncAgentsServer.
// Don't use this type directly, use NewSyncAgentsServerTransport instead.
type SyncAgentsServerTransport struct {
	srv                         *SyncAgentsServer
	beginCreateOrUpdate         *tracker[azfake.PollerResponder[armsql.SyncAgentsClientCreateOrUpdateResponse]]
	beginDelete                 *tracker[azfake.PollerResponder[armsql.SyncAgentsClientDeleteResponse]]
	newListByServerPager        *tracker[azfake.PagerResponder[armsql.SyncAgentsClientListByServerResponse]]
	newListLinkedDatabasesPager *tracker[azfake.PagerResponder[armsql.SyncAgentsClientListLinkedDatabasesResponse]]
}

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

func (s *SyncAgentsServerTransport) 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 syncAgentsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = syncAgentsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "SyncAgentsClient.BeginCreateOrUpdate":
				res.resp, res.err = s.dispatchBeginCreateOrUpdate(req)
			case "SyncAgentsClient.BeginDelete":
				res.resp, res.err = s.dispatchBeginDelete(req)
			case "SyncAgentsClient.GenerateKey":
				res.resp, res.err = s.dispatchGenerateKey(req)
			case "SyncAgentsClient.Get":
				res.resp, res.err = s.dispatchGet(req)
			case "SyncAgentsClient.NewListByServerPager":
				res.resp, res.err = s.dispatchNewListByServerPager(req)
			case "SyncAgentsClient.NewListLinkedDatabasesPager":
				res.resp, res.err = s.dispatchNewListLinkedDatabasesPager(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 (s *SyncAgentsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if s.srv.BeginCreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")}
	}
	beginCreateOrUpdate := s.beginCreateOrUpdate.get(req)
	if beginCreateOrUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Sql/servers/(?P<serverName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/syncAgents/(?P<syncAgentName>[!#&$-;=?-\[\]_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[armsql.SyncAgent](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		serverNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serverName")])
		if err != nil {
			return nil, err
		}
		syncAgentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("syncAgentName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := s.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, serverNameParam, syncAgentNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateOrUpdate = &respr
		s.beginCreateOrUpdate.add(req, beginCreateOrUpdate)
	}

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

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

	return resp, nil
}

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

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

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

	return resp, nil
}

func (s *SyncAgentsServerTransport) dispatchGenerateKey(req *http.Request) (*http.Response, error) {
	if s.srv.GenerateKey == nil {
		return nil, &nonRetriableError{errors.New("fake for method GenerateKey not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Sql/servers/(?P<serverName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/syncAgents/(?P<syncAgentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/generateKey`
	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
	}
	serverNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serverName")])
	if err != nil {
		return nil, err
	}
	syncAgentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("syncAgentName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.GenerateKey(req.Context(), resourceGroupNameParam, serverNameParam, syncAgentNameParam, 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).SyncAgentKeyProperties, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (s *SyncAgentsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if s.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\.Sql/servers/(?P<serverName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/syncAgents/(?P<syncAgentName>[!#&$-;=?-\[\]_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
	}
	serverNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serverName")])
	if err != nil {
		return nil, err
	}
	syncAgentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("syncAgentName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.Get(req.Context(), resourceGroupNameParam, serverNameParam, syncAgentNameParam, 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).SyncAgent, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (s *SyncAgentsServerTransport) dispatchNewListByServerPager(req *http.Request) (*http.Response, error) {
	if s.srv.NewListByServerPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByServerPager not implemented")}
	}
	newListByServerPager := s.newListByServerPager.get(req)
	if newListByServerPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Sql/servers/(?P<serverName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/syncAgents`
		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
		}
		serverNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serverName")])
		if err != nil {
			return nil, err
		}
		resp := s.srv.NewListByServerPager(resourceGroupNameParam, serverNameParam, nil)
		newListByServerPager = &resp
		s.newListByServerPager.add(req, newListByServerPager)
		server.PagerResponderInjectNextLinks(newListByServerPager, req, func(page *armsql.SyncAgentsClientListByServerResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByServerPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		s.newListByServerPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByServerPager) {
		s.newListByServerPager.remove(req)
	}
	return resp, nil
}

func (s *SyncAgentsServerTransport) dispatchNewListLinkedDatabasesPager(req *http.Request) (*http.Response, error) {
	if s.srv.NewListLinkedDatabasesPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListLinkedDatabasesPager not implemented")}
	}
	newListLinkedDatabasesPager := s.newListLinkedDatabasesPager.get(req)
	if newListLinkedDatabasesPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Sql/servers/(?P<serverName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/syncAgents/(?P<syncAgentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/linkedDatabases`
		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
		}
		serverNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serverName")])
		if err != nil {
			return nil, err
		}
		syncAgentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("syncAgentName")])
		if err != nil {
			return nil, err
		}
		resp := s.srv.NewListLinkedDatabasesPager(resourceGroupNameParam, serverNameParam, syncAgentNameParam, nil)
		newListLinkedDatabasesPager = &resp
		s.newListLinkedDatabasesPager.add(req, newListLinkedDatabasesPager)
		server.PagerResponderInjectNextLinks(newListLinkedDatabasesPager, req, func(page *armsql.SyncAgentsClientListLinkedDatabasesResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListLinkedDatabasesPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		s.newListLinkedDatabasesPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListLinkedDatabasesPager) {
		s.newListLinkedDatabasesPager.remove(req)
	}
	return resp, nil
}

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