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

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

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

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

	// GetHistory is the fake for method SmartGroupsClient.GetHistory
	// HTTP status codes to indicate success: http.StatusOK
	GetHistory func(ctx context.Context, smartGroupID string, options *armalertsmanagement.SmartGroupsClientGetHistoryOptions) (resp azfake.Responder[armalertsmanagement.SmartGroupsClientGetHistoryResponse], errResp azfake.ErrorResponder)
}

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

// SmartGroupsServerTransport connects instances of armalertsmanagement.SmartGroupsClient to instances of SmartGroupsServer.
// Don't use this type directly, use NewSmartGroupsServerTransport instead.
type SmartGroupsServerTransport struct {
	srv            *SmartGroupsServer
	newGetAllPager *tracker[azfake.PagerResponder[armalertsmanagement.SmartGroupsClientGetAllResponse]]
}

// Do implements the policy.Transporter interface for SmartGroupsServerTransport.
func (s *SmartGroupsServerTransport) 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 "SmartGroupsClient.ChangeState":
		resp, err = s.dispatchChangeState(req)
	case "SmartGroupsClient.NewGetAllPager":
		resp, err = s.dispatchNewGetAllPager(req)
	case "SmartGroupsClient.GetByID":
		resp, err = s.dispatchGetByID(req)
	case "SmartGroupsClient.GetHistory":
		resp, err = s.dispatchGetHistory(req)
	default:
		err = fmt.Errorf("unhandled API %s", method)
	}

	if err != nil {
		return nil, err
	}

	return resp, nil
}

func (s *SmartGroupsServerTransport) dispatchChangeState(req *http.Request) (*http.Response, error) {
	if s.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/smartGroups/(?P<smartGroupId>[!#&$-;=?-\[\]_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()
	smartGroupIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("smartGroupId")])
	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
	}
	respr, errRespr := s.srv.ChangeState(req.Context(), smartGroupIDParam, newStateParam, 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).SmartGroup, req)
	if err != nil {
		return nil, err
	}
	if val := server.GetResponse(respr).XMSRequestID; val != nil {
		resp.Header.Set("x-ms-request-id", *val)
	}
	return resp, nil
}

func (s *SmartGroupsServerTransport) dispatchNewGetAllPager(req *http.Request) (*http.Response, error) {
	if s.srv.NewGetAllPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewGetAllPager not implemented")}
	}
	newGetAllPager := s.newGetAllPager.get(req)
	if newGetAllPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/smartGroups`
		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)
		targetResourceGroupUnescaped, err := url.QueryUnescape(qp.Get("targetResourceGroup"))
		if err != nil {
			return nil, err
		}
		targetResourceGroupParam := getOptional(targetResourceGroupUnescaped)
		targetResourceTypeUnescaped, err := url.QueryUnescape(qp.Get("targetResourceType"))
		if err != nil {
			return nil, err
		}
		targetResourceTypeParam := getOptional(targetResourceTypeUnescaped)
		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))
		smartGroupStateUnescaped, err := url.QueryUnescape(qp.Get("smartGroupState"))
		if err != nil {
			return nil, err
		}
		smartGroupStateParam := getOptional(armalertsmanagement.AlertState(smartGroupStateUnescaped))
		timeRangeUnescaped, err := url.QueryUnescape(qp.Get("timeRange"))
		if err != nil {
			return nil, err
		}
		timeRangeParam := getOptional(armalertsmanagement.TimeRange(timeRangeUnescaped))
		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.SmartGroupsSortByFields(sortByUnescaped))
		sortOrderUnescaped, err := url.QueryUnescape(qp.Get("sortOrder"))
		if err != nil {
			return nil, err
		}
		sortOrderParam := getOptional(armalertsmanagement.SortOrder(sortOrderUnescaped))
		var options *armalertsmanagement.SmartGroupsClientGetAllOptions
		if targetResourceParam != nil || targetResourceGroupParam != nil || targetResourceTypeParam != nil || monitorServiceParam != nil || monitorConditionParam != nil || severityParam != nil || smartGroupStateParam != nil || timeRangeParam != nil || pageCountParam != nil || sortByParam != nil || sortOrderParam != nil {
			options = &armalertsmanagement.SmartGroupsClientGetAllOptions{
				TargetResource:      targetResourceParam,
				TargetResourceGroup: targetResourceGroupParam,
				TargetResourceType:  targetResourceTypeParam,
				MonitorService:      monitorServiceParam,
				MonitorCondition:    monitorConditionParam,
				Severity:            severityParam,
				SmartGroupState:     smartGroupStateParam,
				TimeRange:           timeRangeParam,
				PageCount:           pageCountParam,
				SortBy:              sortByParam,
				SortOrder:           sortOrderParam,
			}
		}
		resp := s.srv.NewGetAllPager(options)
		newGetAllPager = &resp
		s.newGetAllPager.add(req, newGetAllPager)
		server.PagerResponderInjectNextLinks(newGetAllPager, req, func(page *armalertsmanagement.SmartGroupsClientGetAllResponse, 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) {
		s.newGetAllPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newGetAllPager) {
		s.newGetAllPager.remove(req)
	}
	return resp, nil
}

func (s *SmartGroupsServerTransport) dispatchGetByID(req *http.Request) (*http.Response, error) {
	if s.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/smartGroups/(?P<smartGroupId>[!#&$-;=?-\[\]_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)
	}
	smartGroupIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("smartGroupId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.GetByID(req.Context(), smartGroupIDParam, 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).SmartGroup, req)
	if err != nil {
		return nil, err
	}
	if val := server.GetResponse(respr).XMSRequestID; val != nil {
		resp.Header.Set("x-ms-request-id", *val)
	}
	return resp, nil
}

func (s *SmartGroupsServerTransport) dispatchGetHistory(req *http.Request) (*http.Response, error) {
	if s.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/smartGroups/(?P<smartGroupId>[!#&$-;=?-\[\]_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)
	}
	smartGroupIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("smartGroupId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.GetHistory(req.Context(), smartGroupIDParam, 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).SmartGroupModification, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}
