// 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/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/tenantactivitylogalerts/armtenantactivitylogalerts"
	"net/http"
	"net/url"
	"regexp"
	"slices"
)

// Server is a fake server for instances of the armtenantactivitylogalerts.Client type.
type Server struct {
	// CreateOrUpdate is the fake for method Client.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrUpdate func(ctx context.Context, managementGroupName string, alertRuleName string, tenantActivityLogAlertRule armtenantactivitylogalerts.TenantActivityLogAlertResource, options *armtenantactivitylogalerts.ClientCreateOrUpdateOptions) (resp azfake.Responder[armtenantactivitylogalerts.ClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method Client.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, managementGroupName string, alertRuleName string, options *armtenantactivitylogalerts.ClientDeleteOptions) (resp azfake.Responder[armtenantactivitylogalerts.ClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method Client.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, managementGroupName string, alertRuleName string, options *armtenantactivitylogalerts.ClientGetOptions) (resp azfake.Responder[armtenantactivitylogalerts.ClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByManagementGroupPager is the fake for method Client.NewListByManagementGroupPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByManagementGroupPager func(managementGroupName string, options *armtenantactivitylogalerts.ClientListByManagementGroupOptions) (resp azfake.PagerResponder[armtenantactivitylogalerts.ClientListByManagementGroupResponse])

	// NewListByTenantPager is the fake for method Client.NewListByTenantPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByTenantPager func(options *armtenantactivitylogalerts.ClientListByTenantOptions) (resp azfake.PagerResponder[armtenantactivitylogalerts.ClientListByTenantResponse])

	// Update is the fake for method Client.Update
	// HTTP status codes to indicate success: http.StatusOK
	Update func(ctx context.Context, managementGroupName string, alertRuleName string, tenantActivityLogAlertRulePatch armtenantactivitylogalerts.TenantAlertRulePatchObject, options *armtenantactivitylogalerts.ClientUpdateOptions) (resp azfake.Responder[armtenantactivitylogalerts.ClientUpdateResponse], errResp azfake.ErrorResponder)
}

// NewServerTransport creates a new instance of ServerTransport with the provided implementation.
// The returned ServerTransport instance is connected to an instance of armtenantactivitylogalerts.Client via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewServerTransport(srv *Server) *ServerTransport {
	return &ServerTransport{
		srv:                           srv,
		newListByManagementGroupPager: newTracker[azfake.PagerResponder[armtenantactivitylogalerts.ClientListByManagementGroupResponse]](),
		newListByTenantPager:          newTracker[azfake.PagerResponder[armtenantactivitylogalerts.ClientListByTenantResponse]](),
	}
}

// ServerTransport connects instances of armtenantactivitylogalerts.Client to instances of Server.
// Don't use this type directly, use NewServerTransport instead.
type ServerTransport struct {
	srv                           *Server
	newListByManagementGroupPager *tracker[azfake.PagerResponder[armtenantactivitylogalerts.ClientListByManagementGroupResponse]]
	newListByTenantPager          *tracker[azfake.PagerResponder[armtenantactivitylogalerts.ClientListByTenantResponse]]
}

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

func (s *ServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if serverTransportInterceptor != nil {
			res.resp, res.err, intercepted = serverTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "Client.CreateOrUpdate":
				res.resp, res.err = s.dispatchCreateOrUpdate(req)
			case "Client.Delete":
				res.resp, res.err = s.dispatchDelete(req)
			case "Client.Get":
				res.resp, res.err = s.dispatchGet(req)
			case "Client.NewListByManagementGroupPager":
				res.resp, res.err = s.dispatchNewListByManagementGroupPager(req)
			case "Client.NewListByTenantPager":
				res.resp, res.err = s.dispatchNewListByTenantPager(req)
			case "Client.Update":
				res.resp, res.err = s.dispatchUpdate(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 (s *ServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if s.srv.CreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")}
	}
	const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P<managementGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/tenantActivityLogAlerts/(?P<alertRuleName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 3 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armtenantactivitylogalerts.TenantActivityLogAlertResource](req)
	if err != nil {
		return nil, err
	}
	managementGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managementGroupName")])
	if err != nil {
		return nil, err
	}
	alertRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertRuleName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.CreateOrUpdate(req.Context(), managementGroupNameParam, alertRuleNameParam, body, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).TenantActivityLogAlertResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (s *ServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if s.srv.Delete == nil {
		return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")}
	}
	const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P<managementGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/tenantActivityLogAlerts/(?P<alertRuleName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 3 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	managementGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managementGroupName")])
	if err != nil {
		return nil, err
	}
	alertRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertRuleName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.Delete(req.Context(), managementGroupNameParam, alertRuleNameParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)}
	}
	resp, err := server.NewResponse(respContent, req, nil)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (s *ServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if s.srv.Get == nil {
		return nil, &nonRetriableError{errors.New("fake for method Get not implemented")}
	}
	const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P<managementGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/tenantActivityLogAlerts/(?P<alertRuleName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 3 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	managementGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managementGroupName")])
	if err != nil {
		return nil, err
	}
	alertRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertRuleName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.Get(req.Context(), managementGroupNameParam, alertRuleNameParam, nil)
	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).TenantActivityLogAlertResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (s *ServerTransport) dispatchNewListByManagementGroupPager(req *http.Request) (*http.Response, error) {
	if s.srv.NewListByManagementGroupPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByManagementGroupPager not implemented")}
	}
	newListByManagementGroupPager := s.newListByManagementGroupPager.get(req)
	if newListByManagementGroupPager == nil {
		const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P<managementGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/tenantActivityLogAlerts`
		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)
		}
		managementGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managementGroupName")])
		if err != nil {
			return nil, err
		}
		resp := s.srv.NewListByManagementGroupPager(managementGroupNameParam, nil)
		newListByManagementGroupPager = &resp
		s.newListByManagementGroupPager.add(req, newListByManagementGroupPager)
		server.PagerResponderInjectNextLinks(newListByManagementGroupPager, req, func(page *armtenantactivitylogalerts.ClientListByManagementGroupResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByManagementGroupPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		s.newListByManagementGroupPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByManagementGroupPager) {
		s.newListByManagementGroupPager.remove(req)
	}
	return resp, nil
}

func (s *ServerTransport) dispatchNewListByTenantPager(req *http.Request) (*http.Response, error) {
	if s.srv.NewListByTenantPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByTenantPager not implemented")}
	}
	newListByTenantPager := s.newListByTenantPager.get(req)
	if newListByTenantPager == nil {
		resp := s.srv.NewListByTenantPager(nil)
		newListByTenantPager = &resp
		s.newListByTenantPager.add(req, newListByTenantPager)
		server.PagerResponderInjectNextLinks(newListByTenantPager, req, func(page *armtenantactivitylogalerts.ClientListByTenantResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByTenantPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		s.newListByTenantPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByTenantPager) {
		s.newListByTenantPager.remove(req)
	}
	return resp, nil
}

func (s *ServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) {
	if s.srv.Update == nil {
		return nil, &nonRetriableError{errors.New("fake for method Update not implemented")}
	}
	const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P<managementGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/tenantActivityLogAlerts/(?P<alertRuleName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 3 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armtenantactivitylogalerts.TenantAlertRulePatchObject](req)
	if err != nil {
		return nil, err
	}
	managementGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managementGroupName")])
	if err != nil {
		return nil, err
	}
	alertRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertRuleName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.Update(req.Context(), managementGroupNameParam, alertRuleNameParam, body, nil)
	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).TenantActivityLogAlertResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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