//go:build go1.18
// +build go1.18

// 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/alertsmanagement/armalertsmanagement"
	"net/http"
	"net/url"
	"reflect"
	"regexp"
	"strconv"
)

// AlertsServer is a fake server for instances of the armalertsmanagement.AlertsClient type.
type AlertsServer struct {
	// ChangeState is the fake for method AlertsClient.ChangeState
	// HTTP status codes to indicate success: http.StatusOK
	ChangeState func(ctx context.Context, alertID string, newState armalertsmanagement.AlertState, options *armalertsmanagement.AlertsClientChangeStateOptions) (resp azfake.Responder[armalertsmanagement.AlertsClientChangeStateResponse], errResp azfake.ErrorResponder)

	// NewGetAllPager is the fake for method AlertsClient.NewGetAllPager
	// HTTP status codes to indicate success: http.StatusOK
	NewGetAllPager func(options *armalertsmanagement.AlertsClientGetAllOptions) (resp azfake.PagerResponder[armalertsmanagement.AlertsClientGetAllResponse])

	// GetByID is the fake for method AlertsClient.GetByID
	// HTTP status codes to indicate success: http.StatusOK
	GetByID func(ctx context.Context, alertID string, options *armalertsmanagement.AlertsClientGetByIDOptions) (resp azfake.Responder[armalertsmanagement.AlertsClientGetByIDResponse], errResp azfake.ErrorResponder)

	// GetHistory is the fake for method AlertsClient.GetHistory
	// HTTP status codes to indicate success: http.StatusOK
	GetHistory func(ctx context.Context, alertID string, options *armalertsmanagement.AlertsClientGetHistoryOptions) (resp azfake.Responder[armalertsmanagement.AlertsClientGetHistoryResponse], errResp azfake.ErrorResponder)

	// GetSummary is the fake for method AlertsClient.GetSummary
	// HTTP status codes to indicate success: http.StatusOK
	GetSummary func(ctx context.Context, groupby armalertsmanagement.AlertsSummaryGroupByFields, options *armalertsmanagement.AlertsClientGetSummaryOptions) (resp azfake.Responder[armalertsmanagement.AlertsClientGetSummaryResponse], errResp azfake.ErrorResponder)

	// MetaData is the fake for method AlertsClient.MetaData
	// HTTP status codes to indicate success: http.StatusOK
	MetaData func(ctx context.Context, identifier armalertsmanagement.Identifier, options *armalertsmanagement.AlertsClientMetaDataOptions) (resp azfake.Responder[armalertsmanagement.AlertsClientMetaDataResponse], errResp azfake.ErrorResponder)
}

// NewAlertsServerTransport creates a new instance of AlertsServerTransport with the provided implementation.
// The returned AlertsServerTransport instance is connected to an instance of armalertsmanagement.AlertsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewAlertsServerTransport(srv *AlertsServer) *AlertsServerTransport {
	return &AlertsServerTransport{
		srv:            srv,
		newGetAllPager: newTracker[azfake.PagerResponder[armalertsmanagement.AlertsClientGetAllResponse]](),
	}
}

// AlertsServerTransport connects instances of armalertsmanagement.AlertsClient to instances of AlertsServer.
// Don't use this type directly, use NewAlertsServerTransport instead.
type AlertsServerTransport struct {
	srv            *AlertsServer
	newGetAllPager *tracker[azfake.PagerResponder[armalertsmanagement.AlertsClientGetAllResponse]]
}

// Do implements the policy.Transporter interface for AlertsServerTransport.
func (a *AlertsServerTransport) 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")}
	}

	var resp *http.Response
	var err error

	switch method {
	case "AlertsClient.ChangeState":
		resp, err = a.dispatchChangeState(req)
	case "AlertsClient.NewGetAllPager":
		resp, err = a.dispatchNewGetAllPager(req)
	case "AlertsClient.GetByID":
		resp, err = a.dispatchGetByID(req)
	case "AlertsClient.GetHistory":
		resp, err = a.dispatchGetHistory(req)
	case "AlertsClient.GetSummary":
		resp, err = a.dispatchGetSummary(req)
	case "AlertsClient.MetaData":
		resp, err = a.dispatchMetaData(req)
	default:
		err = fmt.Errorf("unhandled API %s", method)
	}

	if err != nil {
		return nil, err
	}

	return resp, nil
}

func (a *AlertsServerTransport) dispatchChangeState(req *http.Request) (*http.Response, error) {
	if a.srv.ChangeState == nil {
		return nil, &nonRetriableError{errors.New("fake for method ChangeState not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/alerts/(?P<alertId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/changestate`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 2 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	qp := req.URL.Query()
	body, err := server.UnmarshalRequestAsJSON[armalertsmanagement.Comments](req)
	if err != nil {
		return nil, err
	}
	alertIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertId")])
	if err != nil {
		return nil, err
	}
	newStateParam, err := parseWithCast(qp.Get("newState"), func(v string) (armalertsmanagement.AlertState, error) {
		p, unescapeErr := url.QueryUnescape(v)
		if unescapeErr != nil {
			return "", unescapeErr
		}
		return armalertsmanagement.AlertState(p), nil
	})
	if err != nil {
		return nil, err
	}
	var options *armalertsmanagement.AlertsClientChangeStateOptions
	if !reflect.ValueOf(body).IsZero() {
		options = &armalertsmanagement.AlertsClientChangeStateOptions{
			Comment: &body,
		}
	}
	respr, errRespr := a.srv.ChangeState(req.Context(), alertIDParam, newStateParam, options)
	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).Alert, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *AlertsServerTransport) dispatchNewGetAllPager(req *http.Request) (*http.Response, error) {
	if a.srv.NewGetAllPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewGetAllPager not implemented")}
	}
	newGetAllPager := a.newGetAllPager.get(req)
	if newGetAllPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/alerts`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 1 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		qp := req.URL.Query()
		targetResourceUnescaped, err := url.QueryUnescape(qp.Get("targetResource"))
		if err != nil {
			return nil, err
		}
		targetResourceParam := getOptional(targetResourceUnescaped)
		targetResourceTypeUnescaped, err := url.QueryUnescape(qp.Get("targetResourceType"))
		if err != nil {
			return nil, err
		}
		targetResourceTypeParam := getOptional(targetResourceTypeUnescaped)
		targetResourceGroupUnescaped, err := url.QueryUnescape(qp.Get("targetResourceGroup"))
		if err != nil {
			return nil, err
		}
		targetResourceGroupParam := getOptional(targetResourceGroupUnescaped)
		monitorServiceUnescaped, err := url.QueryUnescape(qp.Get("monitorService"))
		if err != nil {
			return nil, err
		}
		monitorServiceParam := getOptional(armalertsmanagement.MonitorService(monitorServiceUnescaped))
		monitorConditionUnescaped, err := url.QueryUnescape(qp.Get("monitorCondition"))
		if err != nil {
			return nil, err
		}
		monitorConditionParam := getOptional(armalertsmanagement.MonitorCondition(monitorConditionUnescaped))
		severityUnescaped, err := url.QueryUnescape(qp.Get("severity"))
		if err != nil {
			return nil, err
		}
		severityParam := getOptional(armalertsmanagement.Severity(severityUnescaped))
		alertStateUnescaped, err := url.QueryUnescape(qp.Get("alertState"))
		if err != nil {
			return nil, err
		}
		alertStateParam := getOptional(armalertsmanagement.AlertState(alertStateUnescaped))
		alertRuleUnescaped, err := url.QueryUnescape(qp.Get("alertRule"))
		if err != nil {
			return nil, err
		}
		alertRuleParam := getOptional(alertRuleUnescaped)
		smartGroupIDUnescaped, err := url.QueryUnescape(qp.Get("smartGroupId"))
		if err != nil {
			return nil, err
		}
		smartGroupIDParam := getOptional(smartGroupIDUnescaped)
		includeContextUnescaped, err := url.QueryUnescape(qp.Get("includeContext"))
		if err != nil {
			return nil, err
		}
		includeContextParam, err := parseOptional(includeContextUnescaped, strconv.ParseBool)
		if err != nil {
			return nil, err
		}
		includeEgressConfigUnescaped, err := url.QueryUnescape(qp.Get("includeEgressConfig"))
		if err != nil {
			return nil, err
		}
		includeEgressConfigParam, err := parseOptional(includeEgressConfigUnescaped, strconv.ParseBool)
		if err != nil {
			return nil, err
		}
		pageCountUnescaped, err := url.QueryUnescape(qp.Get("pageCount"))
		if err != nil {
			return nil, err
		}
		pageCountParam, err := parseOptional(pageCountUnescaped, func(v string) (int64, error) {
			p, parseErr := strconv.ParseInt(v, 10, 64)
			if parseErr != nil {
				return 0, parseErr
			}
			return p, nil
		})
		if err != nil {
			return nil, err
		}
		sortByUnescaped, err := url.QueryUnescape(qp.Get("sortBy"))
		if err != nil {
			return nil, err
		}
		sortByParam := getOptional(armalertsmanagement.AlertsSortByFields(sortByUnescaped))
		sortOrderUnescaped, err := url.QueryUnescape(qp.Get("sortOrder"))
		if err != nil {
			return nil, err
		}
		sortOrderParam := getOptional(armalertsmanagement.SortOrder(sortOrderUnescaped))
		selectUnescaped, err := url.QueryUnescape(qp.Get("select"))
		if err != nil {
			return nil, err
		}
		selectParam := getOptional(selectUnescaped)
		timeRangeUnescaped, err := url.QueryUnescape(qp.Get("timeRange"))
		if err != nil {
			return nil, err
		}
		timeRangeParam := getOptional(armalertsmanagement.TimeRange(timeRangeUnescaped))
		customTimeRangeUnescaped, err := url.QueryUnescape(qp.Get("customTimeRange"))
		if err != nil {
			return nil, err
		}
		customTimeRangeParam := getOptional(customTimeRangeUnescaped)
		var options *armalertsmanagement.AlertsClientGetAllOptions
		if targetResourceParam != nil || targetResourceTypeParam != nil || targetResourceGroupParam != nil || monitorServiceParam != nil || monitorConditionParam != nil || severityParam != nil || alertStateParam != nil || alertRuleParam != nil || smartGroupIDParam != nil || includeContextParam != nil || includeEgressConfigParam != nil || pageCountParam != nil || sortByParam != nil || sortOrderParam != nil || selectParam != nil || timeRangeParam != nil || customTimeRangeParam != nil {
			options = &armalertsmanagement.AlertsClientGetAllOptions{
				TargetResource:      targetResourceParam,
				TargetResourceType:  targetResourceTypeParam,
				TargetResourceGroup: targetResourceGroupParam,
				MonitorService:      monitorServiceParam,
				MonitorCondition:    monitorConditionParam,
				Severity:            severityParam,
				AlertState:          alertStateParam,
				AlertRule:           alertRuleParam,
				SmartGroupID:        smartGroupIDParam,
				IncludeContext:      includeContextParam,
				IncludeEgressConfig: includeEgressConfigParam,
				PageCount:           pageCountParam,
				SortBy:              sortByParam,
				SortOrder:           sortOrderParam,
				Select:              selectParam,
				TimeRange:           timeRangeParam,
				CustomTimeRange:     customTimeRangeParam,
			}
		}
		resp := a.srv.NewGetAllPager(options)
		newGetAllPager = &resp
		a.newGetAllPager.add(req, newGetAllPager)
		server.PagerResponderInjectNextLinks(newGetAllPager, req, func(page *armalertsmanagement.AlertsClientGetAllResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newGetAllPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		a.newGetAllPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newGetAllPager) {
		a.newGetAllPager.remove(req)
	}
	return resp, nil
}

func (a *AlertsServerTransport) dispatchGetByID(req *http.Request) (*http.Response, error) {
	if a.srv.GetByID == nil {
		return nil, &nonRetriableError{errors.New("fake for method GetByID not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/alerts/(?P<alertId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 2 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	alertIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := a.srv.GetByID(req.Context(), alertIDParam, 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).Alert, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *AlertsServerTransport) dispatchGetHistory(req *http.Request) (*http.Response, error) {
	if a.srv.GetHistory == nil {
		return nil, &nonRetriableError{errors.New("fake for method GetHistory not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/alerts/(?P<alertId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/history`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 2 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	alertIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := a.srv.GetHistory(req.Context(), alertIDParam, 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).AlertModification, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *AlertsServerTransport) dispatchGetSummary(req *http.Request) (*http.Response, error) {
	if a.srv.GetSummary == nil {
		return nil, &nonRetriableError{errors.New("fake for method GetSummary not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/alertsSummary`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 1 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	qp := req.URL.Query()
	groupbyParam, err := parseWithCast(qp.Get("groupby"), func(v string) (armalertsmanagement.AlertsSummaryGroupByFields, error) {
		p, unescapeErr := url.QueryUnescape(v)
		if unescapeErr != nil {
			return "", unescapeErr
		}
		return armalertsmanagement.AlertsSummaryGroupByFields(p), nil
	})
	if err != nil {
		return nil, err
	}
	includeSmartGroupsCountUnescaped, err := url.QueryUnescape(qp.Get("includeSmartGroupsCount"))
	if err != nil {
		return nil, err
	}
	includeSmartGroupsCountParam, err := parseOptional(includeSmartGroupsCountUnescaped, strconv.ParseBool)
	if err != nil {
		return nil, err
	}
	targetResourceUnescaped, err := url.QueryUnescape(qp.Get("targetResource"))
	if err != nil {
		return nil, err
	}
	targetResourceParam := getOptional(targetResourceUnescaped)
	targetResourceTypeUnescaped, err := url.QueryUnescape(qp.Get("targetResourceType"))
	if err != nil {
		return nil, err
	}
	targetResourceTypeParam := getOptional(targetResourceTypeUnescaped)
	targetResourceGroupUnescaped, err := url.QueryUnescape(qp.Get("targetResourceGroup"))
	if err != nil {
		return nil, err
	}
	targetResourceGroupParam := getOptional(targetResourceGroupUnescaped)
	monitorServiceUnescaped, err := url.QueryUnescape(qp.Get("monitorService"))
	if err != nil {
		return nil, err
	}
	monitorServiceParam := getOptional(armalertsmanagement.MonitorService(monitorServiceUnescaped))
	monitorConditionUnescaped, err := url.QueryUnescape(qp.Get("monitorCondition"))
	if err != nil {
		return nil, err
	}
	monitorConditionParam := getOptional(armalertsmanagement.MonitorCondition(monitorConditionUnescaped))
	severityUnescaped, err := url.QueryUnescape(qp.Get("severity"))
	if err != nil {
		return nil, err
	}
	severityParam := getOptional(armalertsmanagement.Severity(severityUnescaped))
	alertStateUnescaped, err := url.QueryUnescape(qp.Get("alertState"))
	if err != nil {
		return nil, err
	}
	alertStateParam := getOptional(armalertsmanagement.AlertState(alertStateUnescaped))
	alertRuleUnescaped, err := url.QueryUnescape(qp.Get("alertRule"))
	if err != nil {
		return nil, err
	}
	alertRuleParam := getOptional(alertRuleUnescaped)
	timeRangeUnescaped, err := url.QueryUnescape(qp.Get("timeRange"))
	if err != nil {
		return nil, err
	}
	timeRangeParam := getOptional(armalertsmanagement.TimeRange(timeRangeUnescaped))
	customTimeRangeUnescaped, err := url.QueryUnescape(qp.Get("customTimeRange"))
	if err != nil {
		return nil, err
	}
	customTimeRangeParam := getOptional(customTimeRangeUnescaped)
	var options *armalertsmanagement.AlertsClientGetSummaryOptions
	if includeSmartGroupsCountParam != nil || targetResourceParam != nil || targetResourceTypeParam != nil || targetResourceGroupParam != nil || monitorServiceParam != nil || monitorConditionParam != nil || severityParam != nil || alertStateParam != nil || alertRuleParam != nil || timeRangeParam != nil || customTimeRangeParam != nil {
		options = &armalertsmanagement.AlertsClientGetSummaryOptions{
			IncludeSmartGroupsCount: includeSmartGroupsCountParam,
			TargetResource:          targetResourceParam,
			TargetResourceType:      targetResourceTypeParam,
			TargetResourceGroup:     targetResourceGroupParam,
			MonitorService:          monitorServiceParam,
			MonitorCondition:        monitorConditionParam,
			Severity:                severityParam,
			AlertState:              alertStateParam,
			AlertRule:               alertRuleParam,
			TimeRange:               timeRangeParam,
			CustomTimeRange:         customTimeRangeParam,
		}
	}
	respr, errRespr := a.srv.GetSummary(req.Context(), groupbyParam, options)
	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).AlertsSummary, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *AlertsServerTransport) dispatchMetaData(req *http.Request) (*http.Response, error) {
	if a.srv.MetaData == nil {
		return nil, &nonRetriableError{errors.New("fake for method MetaData not implemented")}
	}
	qp := req.URL.Query()
	identifierParam, err := parseWithCast(qp.Get("identifier"), func(v string) (armalertsmanagement.Identifier, error) {
		p, unescapeErr := url.QueryUnescape(v)
		if unescapeErr != nil {
			return "", unescapeErr
		}
		return armalertsmanagement.Identifier(p), nil
	})
	if err != nil {
		return nil, err
	}
	respr, errRespr := a.srv.MetaData(req.Context(), identifierParam, 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).AlertsMetaData, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}
