// 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/resourcemanager/cosmos/armcosmos/v3"
	"net/http"
	"net/url"
	"regexp"
)

// DatabaseServer is a fake server for instances of the armcosmos.DatabaseClient type.
type DatabaseServer struct {
	// NewListMetricDefinitionsPager is the fake for method DatabaseClient.NewListMetricDefinitionsPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListMetricDefinitionsPager func(resourceGroupName string, accountName string, databaseRid string, options *armcosmos.DatabaseClientListMetricDefinitionsOptions) (resp azfake.PagerResponder[armcosmos.DatabaseClientListMetricDefinitionsResponse])

	// NewListMetricsPager is the fake for method DatabaseClient.NewListMetricsPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListMetricsPager func(resourceGroupName string, accountName string, databaseRid string, filter string, options *armcosmos.DatabaseClientListMetricsOptions) (resp azfake.PagerResponder[armcosmos.DatabaseClientListMetricsResponse])

	// NewListUsagesPager is the fake for method DatabaseClient.NewListUsagesPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListUsagesPager func(resourceGroupName string, accountName string, databaseRid string, options *armcosmos.DatabaseClientListUsagesOptions) (resp azfake.PagerResponder[armcosmos.DatabaseClientListUsagesResponse])
}

// NewDatabaseServerTransport creates a new instance of DatabaseServerTransport with the provided implementation.
// The returned DatabaseServerTransport instance is connected to an instance of armcosmos.DatabaseClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewDatabaseServerTransport(srv *DatabaseServer) *DatabaseServerTransport {
	return &DatabaseServerTransport{
		srv:                           srv,
		newListMetricDefinitionsPager: newTracker[azfake.PagerResponder[armcosmos.DatabaseClientListMetricDefinitionsResponse]](),
		newListMetricsPager:           newTracker[azfake.PagerResponder[armcosmos.DatabaseClientListMetricsResponse]](),
		newListUsagesPager:            newTracker[azfake.PagerResponder[armcosmos.DatabaseClientListUsagesResponse]](),
	}
}

// DatabaseServerTransport connects instances of armcosmos.DatabaseClient to instances of DatabaseServer.
// Don't use this type directly, use NewDatabaseServerTransport instead.
type DatabaseServerTransport struct {
	srv                           *DatabaseServer
	newListMetricDefinitionsPager *tracker[azfake.PagerResponder[armcosmos.DatabaseClientListMetricDefinitionsResponse]]
	newListMetricsPager           *tracker[azfake.PagerResponder[armcosmos.DatabaseClientListMetricsResponse]]
	newListUsagesPager            *tracker[azfake.PagerResponder[armcosmos.DatabaseClientListUsagesResponse]]
}

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

func (d *DatabaseServerTransport) 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 databaseServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = databaseServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "DatabaseClient.NewListMetricDefinitionsPager":
				res.resp, res.err = d.dispatchNewListMetricDefinitionsPager(req)
			case "DatabaseClient.NewListMetricsPager":
				res.resp, res.err = d.dispatchNewListMetricsPager(req)
			case "DatabaseClient.NewListUsagesPager":
				res.resp, res.err = d.dispatchNewListUsagesPager(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 (d *DatabaseServerTransport) dispatchNewListMetricDefinitionsPager(req *http.Request) (*http.Response, error) {
	if d.srv.NewListMetricDefinitionsPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListMetricDefinitionsPager not implemented")}
	}
	newListMetricDefinitionsPager := d.newListMetricDefinitionsPager.get(req)
	if newListMetricDefinitionsPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/databaseAccounts/(?P<accountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P<databaseRid>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/metricDefinitions`
		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
		}
		accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")])
		if err != nil {
			return nil, err
		}
		databaseRidParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseRid")])
		if err != nil {
			return nil, err
		}
		resp := d.srv.NewListMetricDefinitionsPager(resourceGroupNameParam, accountNameParam, databaseRidParam, nil)
		newListMetricDefinitionsPager = &resp
		d.newListMetricDefinitionsPager.add(req, newListMetricDefinitionsPager)
	}
	resp, err := server.PagerResponderNext(newListMetricDefinitionsPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		d.newListMetricDefinitionsPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListMetricDefinitionsPager) {
		d.newListMetricDefinitionsPager.remove(req)
	}
	return resp, nil
}

func (d *DatabaseServerTransport) dispatchNewListMetricsPager(req *http.Request) (*http.Response, error) {
	if d.srv.NewListMetricsPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListMetricsPager not implemented")}
	}
	newListMetricsPager := d.newListMetricsPager.get(req)
	if newListMetricsPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/databaseAccounts/(?P<accountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P<databaseRid>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/metrics`
		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)
		}
		qp := req.URL.Query()
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")])
		if err != nil {
			return nil, err
		}
		databaseRidParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseRid")])
		if err != nil {
			return nil, err
		}
		filterParam, err := url.QueryUnescape(qp.Get("$filter"))
		if err != nil {
			return nil, err
		}
		resp := d.srv.NewListMetricsPager(resourceGroupNameParam, accountNameParam, databaseRidParam, filterParam, nil)
		newListMetricsPager = &resp
		d.newListMetricsPager.add(req, newListMetricsPager)
	}
	resp, err := server.PagerResponderNext(newListMetricsPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		d.newListMetricsPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListMetricsPager) {
		d.newListMetricsPager.remove(req)
	}
	return resp, nil
}

func (d *DatabaseServerTransport) dispatchNewListUsagesPager(req *http.Request) (*http.Response, error) {
	if d.srv.NewListUsagesPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListUsagesPager not implemented")}
	}
	newListUsagesPager := d.newListUsagesPager.get(req)
	if newListUsagesPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/databaseAccounts/(?P<accountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P<databaseRid>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/usages`
		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)
		}
		qp := req.URL.Query()
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")])
		if err != nil {
			return nil, err
		}
		databaseRidParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseRid")])
		if err != nil {
			return nil, err
		}
		filterUnescaped, err := url.QueryUnescape(qp.Get("$filter"))
		if err != nil {
			return nil, err
		}
		filterParam := getOptional(filterUnescaped)
		var options *armcosmos.DatabaseClientListUsagesOptions
		if filterParam != nil {
			options = &armcosmos.DatabaseClientListUsagesOptions{
				Filter: filterParam,
			}
		}
		resp := d.srv.NewListUsagesPager(resourceGroupNameParam, accountNameParam, databaseRidParam, options)
		newListUsagesPager = &resp
		d.newListUsagesPager.add(req, newListUsagesPager)
	}
	resp, err := server.PagerResponderNext(newListUsagesPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		d.newListUsagesPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListUsagesPager) {
		d.newListUsagesPager.remove(req)
	}
	return resp, nil
}

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