// 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 (
	"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"
	"strconv"
)

// ManagedDatabaseSecurityEventsServer is a fake server for instances of the armsql.ManagedDatabaseSecurityEventsClient type.
type ManagedDatabaseSecurityEventsServer struct {
	// NewListByDatabasePager is the fake for method ManagedDatabaseSecurityEventsClient.NewListByDatabasePager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByDatabasePager func(resourceGroupName string, managedInstanceName string, databaseName string, options *armsql.ManagedDatabaseSecurityEventsClientListByDatabaseOptions) (resp azfake.PagerResponder[armsql.ManagedDatabaseSecurityEventsClientListByDatabaseResponse])
}

// NewManagedDatabaseSecurityEventsServerTransport creates a new instance of ManagedDatabaseSecurityEventsServerTransport with the provided implementation.
// The returned ManagedDatabaseSecurityEventsServerTransport instance is connected to an instance of armsql.ManagedDatabaseSecurityEventsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewManagedDatabaseSecurityEventsServerTransport(srv *ManagedDatabaseSecurityEventsServer) *ManagedDatabaseSecurityEventsServerTransport {
	return &ManagedDatabaseSecurityEventsServerTransport{
		srv:                    srv,
		newListByDatabasePager: newTracker[azfake.PagerResponder[armsql.ManagedDatabaseSecurityEventsClientListByDatabaseResponse]](),
	}
}

// ManagedDatabaseSecurityEventsServerTransport connects instances of armsql.ManagedDatabaseSecurityEventsClient to instances of ManagedDatabaseSecurityEventsServer.
// Don't use this type directly, use NewManagedDatabaseSecurityEventsServerTransport instead.
type ManagedDatabaseSecurityEventsServerTransport struct {
	srv                    *ManagedDatabaseSecurityEventsServer
	newListByDatabasePager *tracker[azfake.PagerResponder[armsql.ManagedDatabaseSecurityEventsClientListByDatabaseResponse]]
}

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

func (m *ManagedDatabaseSecurityEventsServerTransport) 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 managedDatabaseSecurityEventsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = managedDatabaseSecurityEventsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "ManagedDatabaseSecurityEventsClient.NewListByDatabasePager":
				res.resp, res.err = m.dispatchNewListByDatabasePager(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 (m *ManagedDatabaseSecurityEventsServerTransport) dispatchNewListByDatabasePager(req *http.Request) (*http.Response, error) {
	if m.srv.NewListByDatabasePager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByDatabasePager not implemented")}
	}
	newListByDatabasePager := m.newListByDatabasePager.get(req)
	if newListByDatabasePager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Sql/managedInstances/(?P<managedInstanceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P<databaseName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/securityEvents`
		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
		}
		managedInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedInstanceName")])
		if err != nil {
			return nil, err
		}
		databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")])
		if err != nil {
			return nil, err
		}
		filterUnescaped, err := url.QueryUnescape(qp.Get("$filter"))
		if err != nil {
			return nil, err
		}
		filterParam := getOptional(filterUnescaped)
		skipUnescaped, err := url.QueryUnescape(qp.Get("$skip"))
		if err != nil {
			return nil, err
		}
		skipParam, err := parseOptional(skipUnescaped, 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
		}
		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
		}
		skiptokenUnescaped, err := url.QueryUnescape(qp.Get("$skiptoken"))
		if err != nil {
			return nil, err
		}
		skiptokenParam := getOptional(skiptokenUnescaped)
		var options *armsql.ManagedDatabaseSecurityEventsClientListByDatabaseOptions
		if filterParam != nil || skipParam != nil || topParam != nil || skiptokenParam != nil {
			options = &armsql.ManagedDatabaseSecurityEventsClientListByDatabaseOptions{
				Filter:    filterParam,
				Skip:      skipParam,
				Top:       topParam,
				Skiptoken: skiptokenParam,
			}
		}
		resp := m.srv.NewListByDatabasePager(resourceGroupNameParam, managedInstanceNameParam, databaseNameParam, options)
		newListByDatabasePager = &resp
		m.newListByDatabasePager.add(req, newListByDatabasePager)
		server.PagerResponderInjectNextLinks(newListByDatabasePager, req, func(page *armsql.ManagedDatabaseSecurityEventsClientListByDatabaseResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByDatabasePager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		m.newListByDatabasePager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByDatabasePager) {
		m.newListByDatabasePager.remove(req)
	}
	return resp, nil
}

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