// 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/resourcemanager/monitor/armmonitor"
	"net/http"
	"net/url"
	"reflect"
	"regexp"
	"slices"
	"strconv"
)

// MetricsServer is a fake server for instances of the armmonitor.MetricsClient type.
type MetricsServer struct {
	// List is the fake for method MetricsClient.List
	// HTTP status codes to indicate success: http.StatusOK
	List func(ctx context.Context, resourceURI string, options *armmonitor.MetricsClientListOptions) (resp azfake.Responder[armmonitor.MetricsClientListResponse], errResp azfake.ErrorResponder)

	// ListAtSubscriptionScope is the fake for method MetricsClient.ListAtSubscriptionScope
	// HTTP status codes to indicate success: http.StatusOK
	ListAtSubscriptionScope func(ctx context.Context, region string, options *armmonitor.MetricsClientListAtSubscriptionScopeOptions) (resp azfake.Responder[armmonitor.MetricsClientListAtSubscriptionScopeResponse], errResp azfake.ErrorResponder)

	// ListAtSubscriptionScopePost is the fake for method MetricsClient.ListAtSubscriptionScopePost
	// HTTP status codes to indicate success: http.StatusOK
	ListAtSubscriptionScopePost func(ctx context.Context, region string, options *armmonitor.MetricsClientListAtSubscriptionScopePostOptions) (resp azfake.Responder[armmonitor.MetricsClientListAtSubscriptionScopePostResponse], errResp azfake.ErrorResponder)
}

// NewMetricsServerTransport creates a new instance of MetricsServerTransport with the provided implementation.
// The returned MetricsServerTransport instance is connected to an instance of armmonitor.MetricsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewMetricsServerTransport(srv *MetricsServer) *MetricsServerTransport {
	return &MetricsServerTransport{srv: srv}
}

// MetricsServerTransport connects instances of armmonitor.MetricsClient to instances of MetricsServer.
// Don't use this type directly, use NewMetricsServerTransport instead.
type MetricsServerTransport struct {
	srv *MetricsServer
}

// Do implements the policy.Transporter interface for MetricsServerTransport.
func (m *MetricsServerTransport) 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 *MetricsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if metricsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = metricsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "MetricsClient.List":
				res.resp, res.err = m.dispatchList(req)
			case "MetricsClient.ListAtSubscriptionScope":
				res.resp, res.err = m.dispatchListAtSubscriptionScope(req)
			case "MetricsClient.ListAtSubscriptionScopePost":
				res.resp, res.err = m.dispatchListAtSubscriptionScopePost(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 (m *MetricsServerTransport) dispatchList(req *http.Request) (*http.Response, error) {
	if m.srv.List == nil {
		return nil, &nonRetriableError{errors.New("fake for method List not implemented")}
	}
	const regexStr = `/(?P<resourceUri>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Insights/metrics`
	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()
	resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")])
	if err != nil {
		return nil, err
	}
	timespanParam := getOptional(qp.Get("timespan"))
	intervalParam := getOptional(qp.Get("interval"))
	metricnamesParam := getOptional(qp.Get("metricnames"))
	aggregationParam := getOptional(qp.Get("aggregation"))
	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
	}
	orderbyParam := getOptional(qp.Get("orderby"))
	filterParam := getOptional(qp.Get("$filter"))
	resultTypeParam := getOptional(armmonitor.ResultType(qp.Get("resultType")))
	metricnamespaceParam := getOptional(qp.Get("metricnamespace"))
	autoAdjustTimegrainParam, err := parseOptional(qp.Get("AutoAdjustTimegrain"), strconv.ParseBool)
	if err != nil {
		return nil, err
	}
	validateDimensionsParam, err := parseOptional(qp.Get("ValidateDimensions"), strconv.ParseBool)
	if err != nil {
		return nil, err
	}
	rollupbyParam := getOptional(qp.Get("rollupby"))
	var options *armmonitor.MetricsClientListOptions
	if timespanParam != nil || intervalParam != nil || metricnamesParam != nil || aggregationParam != nil || topParam != nil || orderbyParam != nil || filterParam != nil || resultTypeParam != nil || metricnamespaceParam != nil || autoAdjustTimegrainParam != nil || validateDimensionsParam != nil || rollupbyParam != nil {
		options = &armmonitor.MetricsClientListOptions{
			Timespan:            timespanParam,
			Interval:            intervalParam,
			Metricnames:         metricnamesParam,
			Aggregation:         aggregationParam,
			Top:                 topParam,
			Orderby:             orderbyParam,
			Filter:              filterParam,
			ResultType:          resultTypeParam,
			Metricnamespace:     metricnamespaceParam,
			AutoAdjustTimegrain: autoAdjustTimegrainParam,
			ValidateDimensions:  validateDimensionsParam,
			Rollupby:            rollupbyParam,
		}
	}
	respr, errRespr := m.srv.List(req.Context(), resourceURIParam, 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).Response, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (m *MetricsServerTransport) dispatchListAtSubscriptionScope(req *http.Request) (*http.Response, error) {
	if m.srv.ListAtSubscriptionScope == nil {
		return nil, &nonRetriableError{errors.New("fake for method ListAtSubscriptionScope not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Insights/metrics`
	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()
	timespanParam := getOptional(qp.Get("timespan"))
	intervalParam := getOptional(qp.Get("interval"))
	metricnamesParam := getOptional(qp.Get("metricnames"))
	aggregationParam := getOptional(qp.Get("aggregation"))
	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
	}
	orderbyParam := getOptional(qp.Get("orderby"))
	filterParam := getOptional(qp.Get("$filter"))
	resultTypeParam := getOptional(armmonitor.MetricResultType(qp.Get("resultType")))
	metricnamespaceParam := getOptional(qp.Get("metricnamespace"))
	autoAdjustTimegrainParam, err := parseOptional(qp.Get("AutoAdjustTimegrain"), strconv.ParseBool)
	if err != nil {
		return nil, err
	}
	validateDimensionsParam, err := parseOptional(qp.Get("ValidateDimensions"), strconv.ParseBool)
	if err != nil {
		return nil, err
	}
	rollupbyParam := getOptional(qp.Get("rollupby"))
	var options *armmonitor.MetricsClientListAtSubscriptionScopeOptions
	if timespanParam != nil || intervalParam != nil || metricnamesParam != nil || aggregationParam != nil || topParam != nil || orderbyParam != nil || filterParam != nil || resultTypeParam != nil || metricnamespaceParam != nil || autoAdjustTimegrainParam != nil || validateDimensionsParam != nil || rollupbyParam != nil {
		options = &armmonitor.MetricsClientListAtSubscriptionScopeOptions{
			Timespan:            timespanParam,
			Interval:            intervalParam,
			Metricnames:         metricnamesParam,
			Aggregation:         aggregationParam,
			Top:                 topParam,
			Orderby:             orderbyParam,
			Filter:              filterParam,
			ResultType:          resultTypeParam,
			Metricnamespace:     metricnamespaceParam,
			AutoAdjustTimegrain: autoAdjustTimegrainParam,
			ValidateDimensions:  validateDimensionsParam,
			Rollupby:            rollupbyParam,
		}
	}
	respr, errRespr := m.srv.ListAtSubscriptionScope(req.Context(), qp.Get("region"), 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).Response, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (m *MetricsServerTransport) dispatchListAtSubscriptionScopePost(req *http.Request) (*http.Response, error) {
	if m.srv.ListAtSubscriptionScopePost == nil {
		return nil, &nonRetriableError{errors.New("fake for method ListAtSubscriptionScopePost not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Insights/metrics`
	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()
	body, err := server.UnmarshalRequestAsJSON[armmonitor.SubscriptionScopeMetricsRequestBodyParameters](req)
	if err != nil {
		return nil, err
	}
	timespanParam := getOptional(qp.Get("timespan"))
	intervalParam := getOptional(qp.Get("interval"))
	metricnamesParam := getOptional(qp.Get("metricnames"))
	aggregationParam := getOptional(qp.Get("aggregation"))
	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
	}
	orderbyParam := getOptional(qp.Get("orderby"))
	filterParam := getOptional(qp.Get("$filter"))
	resultTypeParam := getOptional(armmonitor.MetricResultType(qp.Get("resultType")))
	metricnamespaceParam := getOptional(qp.Get("metricnamespace"))
	autoAdjustTimegrainParam, err := parseOptional(qp.Get("AutoAdjustTimegrain"), strconv.ParseBool)
	if err != nil {
		return nil, err
	}
	validateDimensionsParam, err := parseOptional(qp.Get("ValidateDimensions"), strconv.ParseBool)
	if err != nil {
		return nil, err
	}
	rollupbyParam := getOptional(qp.Get("rollupby"))
	var options *armmonitor.MetricsClientListAtSubscriptionScopePostOptions
	if timespanParam != nil || intervalParam != nil || metricnamesParam != nil || aggregationParam != nil || topParam != nil || orderbyParam != nil || filterParam != nil || resultTypeParam != nil || metricnamespaceParam != nil || autoAdjustTimegrainParam != nil || validateDimensionsParam != nil || rollupbyParam != nil || !reflect.ValueOf(body).IsZero() {
		options = &armmonitor.MetricsClientListAtSubscriptionScopePostOptions{
			Timespan:            timespanParam,
			Interval:            intervalParam,
			Metricnames:         metricnamesParam,
			Aggregation:         aggregationParam,
			Top:                 topParam,
			Orderby:             orderbyParam,
			Filter:              filterParam,
			ResultType:          resultTypeParam,
			Metricnamespace:     metricnamespaceParam,
			AutoAdjustTimegrain: autoAdjustTimegrainParam,
			ValidateDimensions:  validateDimensionsParam,
			Rollupby:            rollupbyParam,
			Body:                &body,
		}
	}
	respr, errRespr := m.srv.ListAtSubscriptionScopePost(req.Context(), qp.Get("region"), 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).Response, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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