//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/security/armsecurity"
	"net/http"
	"net/url"
	"reflect"
	"regexp"
)

// GovernanceRulesServer is a fake server for instances of the armsecurity.GovernanceRulesClient type.
type GovernanceRulesServer struct {
	// CreateOrUpdate is the fake for method GovernanceRulesClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrUpdate func(ctx context.Context, scope string, ruleID string, governanceRule armsecurity.GovernanceRule, options *armsecurity.GovernanceRulesClientCreateOrUpdateOptions) (resp azfake.Responder[armsecurity.GovernanceRulesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method GovernanceRulesClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, scope string, ruleID string, options *armsecurity.GovernanceRulesClientBeginDeleteOptions) (resp azfake.PollerResponder[armsecurity.GovernanceRulesClientDeleteResponse], errResp azfake.ErrorResponder)

	// BeginExecute is the fake for method GovernanceRulesClient.BeginExecute
	// HTTP status codes to indicate success: http.StatusAccepted
	BeginExecute func(ctx context.Context, scope string, ruleID string, options *armsecurity.GovernanceRulesClientBeginExecuteOptions) (resp azfake.PollerResponder[armsecurity.GovernanceRulesClientExecuteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method GovernanceRulesClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, scope string, ruleID string, options *armsecurity.GovernanceRulesClientGetOptions) (resp azfake.Responder[armsecurity.GovernanceRulesClientGetResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method GovernanceRulesClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(scope string, options *armsecurity.GovernanceRulesClientListOptions) (resp azfake.PagerResponder[armsecurity.GovernanceRulesClientListResponse])

	// OperationResults is the fake for method GovernanceRulesClient.OperationResults
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	OperationResults func(ctx context.Context, scope string, ruleID string, operationID string, options *armsecurity.GovernanceRulesClientOperationResultsOptions) (resp azfake.Responder[armsecurity.GovernanceRulesClientOperationResultsResponse], errResp azfake.ErrorResponder)
}

// NewGovernanceRulesServerTransport creates a new instance of GovernanceRulesServerTransport with the provided implementation.
// The returned GovernanceRulesServerTransport instance is connected to an instance of armsecurity.GovernanceRulesClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewGovernanceRulesServerTransport(srv *GovernanceRulesServer) *GovernanceRulesServerTransport {
	return &GovernanceRulesServerTransport{
		srv:          srv,
		beginDelete:  newTracker[azfake.PollerResponder[armsecurity.GovernanceRulesClientDeleteResponse]](),
		beginExecute: newTracker[azfake.PollerResponder[armsecurity.GovernanceRulesClientExecuteResponse]](),
		newListPager: newTracker[azfake.PagerResponder[armsecurity.GovernanceRulesClientListResponse]](),
	}
}

// GovernanceRulesServerTransport connects instances of armsecurity.GovernanceRulesClient to instances of GovernanceRulesServer.
// Don't use this type directly, use NewGovernanceRulesServerTransport instead.
type GovernanceRulesServerTransport struct {
	srv          *GovernanceRulesServer
	beginDelete  *tracker[azfake.PollerResponder[armsecurity.GovernanceRulesClientDeleteResponse]]
	beginExecute *tracker[azfake.PollerResponder[armsecurity.GovernanceRulesClientExecuteResponse]]
	newListPager *tracker[azfake.PagerResponder[armsecurity.GovernanceRulesClientListResponse]]
}

// Do implements the policy.Transporter interface for GovernanceRulesServerTransport.
func (g *GovernanceRulesServerTransport) 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 "GovernanceRulesClient.CreateOrUpdate":
		resp, err = g.dispatchCreateOrUpdate(req)
	case "GovernanceRulesClient.BeginDelete":
		resp, err = g.dispatchBeginDelete(req)
	case "GovernanceRulesClient.BeginExecute":
		resp, err = g.dispatchBeginExecute(req)
	case "GovernanceRulesClient.Get":
		resp, err = g.dispatchGet(req)
	case "GovernanceRulesClient.NewListPager":
		resp, err = g.dispatchNewListPager(req)
	case "GovernanceRulesClient.OperationResults":
		resp, err = g.dispatchOperationResults(req)
	default:
		err = fmt.Errorf("unhandled API %s", method)
	}

	if err != nil {
		return nil, err
	}

	return resp, nil
}

func (g *GovernanceRulesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if g.srv.CreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")}
	}
	const regexStr = `/(?P<scope>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Security/governanceRules/(?P<ruleId>[!#&$-;=?-\[\]_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)
	}
	body, err := server.UnmarshalRequestAsJSON[armsecurity.GovernanceRule](req)
	if err != nil {
		return nil, err
	}
	scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")])
	if err != nil {
		return nil, err
	}
	ruleIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("ruleId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := g.srv.CreateOrUpdate(req.Context(), scopeParam, ruleIDParam, body, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !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).GovernanceRule, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (g *GovernanceRulesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if g.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := g.beginDelete.get(req)
	if beginDelete == nil {
		const regexStr = `/(?P<scope>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Security/governanceRules/(?P<ruleId>[!#&$-;=?-\[\]_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)
		}
		scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")])
		if err != nil {
			return nil, err
		}
		ruleIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("ruleId")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := g.srv.BeginDelete(req.Context(), scopeParam, ruleIDParam, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		g.beginDelete.add(req, beginDelete)
	}

	resp, err := server.PollerResponderNext(beginDelete, req)
	if err != nil {
		return nil, err
	}

	if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) {
		g.beginDelete.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)}
	}
	if !server.PollerResponderMore(beginDelete) {
		g.beginDelete.remove(req)
	}

	return resp, nil
}

func (g *GovernanceRulesServerTransport) dispatchBeginExecute(req *http.Request) (*http.Response, error) {
	if g.srv.BeginExecute == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginExecute not implemented")}
	}
	beginExecute := g.beginExecute.get(req)
	if beginExecute == nil {
		const regexStr = `/(?P<scope>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Security/governanceRules/(?P<ruleId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/execute`
		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)
		}
		body, err := server.UnmarshalRequestAsJSON[armsecurity.ExecuteGovernanceRuleParams](req)
		if err != nil {
			return nil, err
		}
		scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")])
		if err != nil {
			return nil, err
		}
		ruleIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("ruleId")])
		if err != nil {
			return nil, err
		}
		var options *armsecurity.GovernanceRulesClientBeginExecuteOptions
		if !reflect.ValueOf(body).IsZero() {
			options = &armsecurity.GovernanceRulesClientBeginExecuteOptions{
				ExecuteGovernanceRuleParams: &body,
			}
		}
		respr, errRespr := g.srv.BeginExecute(req.Context(), scopeParam, ruleIDParam, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginExecute = &respr
		g.beginExecute.add(req, beginExecute)
	}

	resp, err := server.PollerResponderNext(beginExecute, req)
	if err != nil {
		return nil, err
	}

	if !contains([]int{http.StatusAccepted}, resp.StatusCode) {
		g.beginExecute.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusAccepted", resp.StatusCode)}
	}
	if !server.PollerResponderMore(beginExecute) {
		g.beginExecute.remove(req)
	}

	return resp, nil
}

func (g *GovernanceRulesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if g.srv.Get == nil {
		return nil, &nonRetriableError{errors.New("fake for method Get not implemented")}
	}
	const regexStr = `/(?P<scope>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Security/governanceRules/(?P<ruleId>[!#&$-;=?-\[\]_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)
	}
	scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")])
	if err != nil {
		return nil, err
	}
	ruleIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("ruleId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := g.srv.Get(req.Context(), scopeParam, ruleIDParam, 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).GovernanceRule, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (g *GovernanceRulesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if g.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := g.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/(?P<scope>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Security/governanceRules`
		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)
		}
		scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")])
		if err != nil {
			return nil, err
		}
		resp := g.srv.NewListPager(scopeParam, nil)
		newListPager = &resp
		g.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armsecurity.GovernanceRulesClientListResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		g.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		g.newListPager.remove(req)
	}
	return resp, nil
}

func (g *GovernanceRulesServerTransport) dispatchOperationResults(req *http.Request) (*http.Response, error) {
	if g.srv.OperationResults == nil {
		return nil, &nonRetriableError{errors.New("fake for method OperationResults not implemented")}
	}
	const regexStr = `/(?P<scope>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Security/governanceRules/(?P<ruleId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/operationResults/(?P<operationId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 3 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")])
	if err != nil {
		return nil, err
	}
	ruleIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("ruleId")])
	if err != nil {
		return nil, err
	}
	operationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("operationId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := g.srv.OperationResults(req.Context(), scopeParam, ruleIDParam, operationIDParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK, http.StatusAccepted}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).OperationResultAutoGenerated, req)
	if err != nil {
		return nil, err
	}
	if val := server.GetResponse(respr).Location; val != nil {
		resp.Header.Set("location", *val)
	}
	return resp, nil
}
