// 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/resources/armpolicy/v2"
	"net/http"
	"net/url"
	"regexp"
	"slices"
)

// TokensServer is a fake server for instances of the armpolicy.TokensClient type.
type TokensServer struct {
	// Acquire is the fake for method TokensClient.Acquire
	// HTTP status codes to indicate success: http.StatusOK
	Acquire func(ctx context.Context, parameters armpolicy.TokenRequest, options *armpolicy.TokensClientAcquireOptions) (resp azfake.Responder[armpolicy.TokensClientAcquireResponse], errResp azfake.ErrorResponder)

	// AcquireAtManagementGroup is the fake for method TokensClient.AcquireAtManagementGroup
	// HTTP status codes to indicate success: http.StatusOK
	AcquireAtManagementGroup func(ctx context.Context, managementGroupName string, parameters armpolicy.TokenRequest, options *armpolicy.TokensClientAcquireAtManagementGroupOptions) (resp azfake.Responder[armpolicy.TokensClientAcquireAtManagementGroupResponse], errResp azfake.ErrorResponder)
}

// NewTokensServerTransport creates a new instance of TokensServerTransport with the provided implementation.
// The returned TokensServerTransport instance is connected to an instance of armpolicy.TokensClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewTokensServerTransport(srv *TokensServer) *TokensServerTransport {
	return &TokensServerTransport{srv: srv}
}

// TokensServerTransport connects instances of armpolicy.TokensClient to instances of TokensServer.
// Don't use this type directly, use NewTokensServerTransport instead.
type TokensServerTransport struct {
	srv *TokensServer
}

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

func (t *TokensServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if tokensServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = tokensServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "TokensClient.Acquire":
				res.resp, res.err = t.dispatchAcquire(req)
			case "TokensClient.AcquireAtManagementGroup":
				res.resp, res.err = t.dispatchAcquireAtManagementGroup(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 (t *TokensServerTransport) dispatchAcquire(req *http.Request) (*http.Response, error) {
	if t.srv.Acquire == nil {
		return nil, &nonRetriableError{errors.New("fake for method Acquire not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Authorization/acquirePolicyToken`
	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)
	}
	body, err := server.UnmarshalRequestAsJSON[armpolicy.TokenRequest](req)
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.Acquire(req.Context(), 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).TokenResponse, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (t *TokensServerTransport) dispatchAcquireAtManagementGroup(req *http.Request) (*http.Response, error) {
	if t.srv.AcquireAtManagementGroup == nil {
		return nil, &nonRetriableError{errors.New("fake for method AcquireAtManagementGroup not implemented")}
	}
	const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P<managementGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Authorization/acquirePolicyToken`
	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)
	}
	body, err := server.UnmarshalRequestAsJSON[armpolicy.TokenRequest](req)
	if err != nil {
		return nil, err
	}
	managementGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managementGroupName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.AcquireAtManagementGroup(req.Context(), managementGroupNameParam, 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).TokenResponse, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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