// 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/machinelearning/armmachinelearning/v5"
	"net/http"
	"net/url"
	"regexp"
	"slices"
)

// RaiPolicyServer is a fake server for instances of the armmachinelearning.RaiPolicyClient type.
type RaiPolicyServer struct {
	// BeginCreate is the fake for method RaiPolicyClient.BeginCreate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	BeginCreate func(ctx context.Context, resourceGroupName string, workspaceName string, endpointName string, raiPolicyName string, body armmachinelearning.RaiPolicyPropertiesBasicResource, options *armmachinelearning.RaiPolicyClientBeginCreateOptions) (resp azfake.PollerResponder[armmachinelearning.RaiPolicyClientCreateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method RaiPolicyClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, workspaceName string, endpointName string, raiPolicyName string, options *armmachinelearning.RaiPolicyClientBeginDeleteOptions) (resp azfake.PollerResponder[armmachinelearning.RaiPolicyClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method RaiPolicyClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, workspaceName string, endpointName string, raiPolicyName string, options *armmachinelearning.RaiPolicyClientGetOptions) (resp azfake.Responder[armmachinelearning.RaiPolicyClientGetResponse], errResp azfake.ErrorResponder)
}

// NewRaiPolicyServerTransport creates a new instance of RaiPolicyServerTransport with the provided implementation.
// The returned RaiPolicyServerTransport instance is connected to an instance of armmachinelearning.RaiPolicyClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewRaiPolicyServerTransport(srv *RaiPolicyServer) *RaiPolicyServerTransport {
	return &RaiPolicyServerTransport{
		srv:         srv,
		beginCreate: newTracker[azfake.PollerResponder[armmachinelearning.RaiPolicyClientCreateResponse]](),
		beginDelete: newTracker[azfake.PollerResponder[armmachinelearning.RaiPolicyClientDeleteResponse]](),
	}
}

// RaiPolicyServerTransport connects instances of armmachinelearning.RaiPolicyClient to instances of RaiPolicyServer.
// Don't use this type directly, use NewRaiPolicyServerTransport instead.
type RaiPolicyServerTransport struct {
	srv         *RaiPolicyServer
	beginCreate *tracker[azfake.PollerResponder[armmachinelearning.RaiPolicyClientCreateResponse]]
	beginDelete *tracker[azfake.PollerResponder[armmachinelearning.RaiPolicyClientDeleteResponse]]
}

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

func (r *RaiPolicyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if raiPolicyServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = raiPolicyServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "RaiPolicyClient.BeginCreate":
				res.resp, res.err = r.dispatchBeginCreate(req)
			case "RaiPolicyClient.BeginDelete":
				res.resp, res.err = r.dispatchBeginDelete(req)
			case "RaiPolicyClient.Get":
				res.resp, res.err = r.dispatchGet(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 (r *RaiPolicyServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) {
	if r.srv.BeginCreate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")}
	}
	beginCreate := r.beginCreate.get(req)
	if beginCreate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.MachineLearningServices/workspaces/(?P<workspaceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/endpoints/(?P<endpointName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiPolicies/(?P<raiPolicyName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 6 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		qp := req.URL.Query()
		body, err := server.UnmarshalRequestAsJSON[armmachinelearning.RaiPolicyPropertiesBasicResource](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")])
		if err != nil {
			return nil, err
		}
		endpointNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("endpointName")])
		if err != nil {
			return nil, err
		}
		raiPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiPolicyName")])
		if err != nil {
			return nil, err
		}
		proxyAPIVersionParam := getOptional(qp.Get("proxy-api-version"))
		var options *armmachinelearning.RaiPolicyClientBeginCreateOptions
		if proxyAPIVersionParam != nil {
			options = &armmachinelearning.RaiPolicyClientBeginCreateOptions{
				ProxyAPIVersion: proxyAPIVersionParam,
			}
		}
		respr, errRespr := r.srv.BeginCreate(req.Context(), resourceGroupNameParam, workspaceNameParam, endpointNameParam, raiPolicyNameParam, body, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreate = &respr
		r.beginCreate.add(req, beginCreate)
	}

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

	if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) {
		r.beginCreate.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)}
	}
	if !server.PollerResponderMore(beginCreate) {
		r.beginCreate.remove(req)
	}

	return resp, nil
}

func (r *RaiPolicyServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if r.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := r.beginDelete.get(req)
	if beginDelete == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.MachineLearningServices/workspaces/(?P<workspaceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/endpoints/(?P<endpointName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiPolicies/(?P<raiPolicyName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 6 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		qp := req.URL.Query()
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")])
		if err != nil {
			return nil, err
		}
		endpointNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("endpointName")])
		if err != nil {
			return nil, err
		}
		raiPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiPolicyName")])
		if err != nil {
			return nil, err
		}
		proxyAPIVersionParam := getOptional(qp.Get("proxy-api-version"))
		var options *armmachinelearning.RaiPolicyClientBeginDeleteOptions
		if proxyAPIVersionParam != nil {
			options = &armmachinelearning.RaiPolicyClientBeginDeleteOptions{
				ProxyAPIVersion: proxyAPIVersionParam,
			}
		}
		respr, errRespr := r.srv.BeginDelete(req.Context(), resourceGroupNameParam, workspaceNameParam, endpointNameParam, raiPolicyNameParam, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		r.beginDelete.add(req, beginDelete)
	}

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

	if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) {
		r.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) {
		r.beginDelete.remove(req)
	}

	return resp, nil
}

func (r *RaiPolicyServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if r.srv.Get == nil {
		return nil, &nonRetriableError{errors.New("fake for method Get not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.MachineLearningServices/workspaces/(?P<workspaceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/endpoints/(?P<endpointName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiPolicies/(?P<raiPolicyName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")])
	if err != nil {
		return nil, err
	}
	endpointNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("endpointName")])
	if err != nil {
		return nil, err
	}
	raiPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiPolicyName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := r.srv.Get(req.Context(), resourceGroupNameParam, workspaceNameParam, endpointNameParam, raiPolicyNameParam, 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).RaiPolicyPropertiesBasicResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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