// 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/subscription/armsubscription/v2"
	"net/http"
	"net/url"
	"regexp"
)

// Server is a fake server for instances of the armsubscription.Client type.
type Server struct {
	// BeginAcceptOwnership is the fake for method Client.BeginAcceptOwnership
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginAcceptOwnership func(ctx context.Context, subscriptionID string, body armsubscription.AcceptOwnershipRequest, options *armsubscription.ClientBeginAcceptOwnershipOptions) (resp azfake.PollerResponder[armsubscription.ClientAcceptOwnershipResponse], errResp azfake.ErrorResponder)

	// AcceptOwnershipStatus is the fake for method Client.AcceptOwnershipStatus
	// HTTP status codes to indicate success: http.StatusOK
	AcceptOwnershipStatus func(ctx context.Context, subscriptionID string, options *armsubscription.ClientAcceptOwnershipStatusOptions) (resp azfake.Responder[armsubscription.ClientAcceptOwnershipStatusResponse], errResp azfake.ErrorResponder)

	// Cancel is the fake for method Client.Cancel
	// HTTP status codes to indicate success: http.StatusOK
	Cancel func(ctx context.Context, subscriptionID string, options *armsubscription.ClientCancelOptions) (resp azfake.Responder[armsubscription.ClientCancelResponse], errResp azfake.ErrorResponder)

	// Enable is the fake for method Client.Enable
	// HTTP status codes to indicate success: http.StatusOK
	Enable func(ctx context.Context, subscriptionID string, options *armsubscription.ClientEnableOptions) (resp azfake.Responder[armsubscription.ClientEnableResponse], errResp azfake.ErrorResponder)

	// Rename is the fake for method Client.Rename
	// HTTP status codes to indicate success: http.StatusOK
	Rename func(ctx context.Context, subscriptionID string, body armsubscription.Name, options *armsubscription.ClientRenameOptions) (resp azfake.Responder[armsubscription.ClientRenameResponse], errResp azfake.ErrorResponder)
}

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

// ServerTransport connects instances of armsubscription.Client to instances of Server.
// Don't use this type directly, use NewServerTransport instead.
type ServerTransport struct {
	srv                  *Server
	beginAcceptOwnership *tracker[azfake.PollerResponder[armsubscription.ClientAcceptOwnershipResponse]]
}

// 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)
	defer close(resultChan)

	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.BeginAcceptOwnership":
				res.resp, res.err = s.dispatchBeginAcceptOwnership(req)
			case "Client.AcceptOwnershipStatus":
				res.resp, res.err = s.dispatchAcceptOwnershipStatus(req)
			case "Client.Cancel":
				res.resp, res.err = s.dispatchCancel(req)
			case "Client.Enable":
				res.resp, res.err = s.dispatchEnable(req)
			case "Client.Rename":
				res.resp, res.err = s.dispatchRename(req)
			default:
				res.err = fmt.Errorf("unhandled API %s", method)
			}

		}
		select {
		case resultChan <- res:
		case <-req.Context().Done():
		}
	}()

	select {
	case <-req.Context().Done():
		return nil, req.Context().Err()
	case res := <-resultChan:
		return res.resp, res.err
	}
}

func (s *ServerTransport) dispatchBeginAcceptOwnership(req *http.Request) (*http.Response, error) {
	if s.srv.BeginAcceptOwnership == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginAcceptOwnership not implemented")}
	}
	beginAcceptOwnership := s.beginAcceptOwnership.get(req)
	if beginAcceptOwnership == nil {
		const regexStr = `/providers/Microsoft\.Subscription/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/acceptOwnership`
		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[armsubscription.AcceptOwnershipRequest](req)
		if err != nil {
			return nil, err
		}
		subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := s.srv.BeginAcceptOwnership(req.Context(), subscriptionIDParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginAcceptOwnership = &respr
		s.beginAcceptOwnership.add(req, beginAcceptOwnership)
	}

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

	if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) {
		s.beginAcceptOwnership.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(beginAcceptOwnership) {
		s.beginAcceptOwnership.remove(req)
	}

	return resp, nil
}

func (s *ServerTransport) dispatchAcceptOwnershipStatus(req *http.Request) (*http.Response, error) {
	if s.srv.AcceptOwnershipStatus == nil {
		return nil, &nonRetriableError{errors.New("fake for method AcceptOwnershipStatus not implemented")}
	}
	const regexStr = `/providers/Microsoft\.Subscription/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/acceptOwnershipStatus`
	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)
	}
	subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.AcceptOwnershipStatus(req.Context(), subscriptionIDParam, 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).AcceptOwnershipStatusResponse, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (s *ServerTransport) dispatchCancel(req *http.Request) (*http.Response, error) {
	if s.srv.Cancel == nil {
		return nil, &nonRetriableError{errors.New("fake for method Cancel not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Subscription/cancel`
	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)
	}
	subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.Cancel(req.Context(), subscriptionIDParam, 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).CanceledSubscriptionID, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (s *ServerTransport) dispatchEnable(req *http.Request) (*http.Response, error) {
	if s.srv.Enable == nil {
		return nil, &nonRetriableError{errors.New("fake for method Enable not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Subscription/enable`
	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)
	}
	subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.Enable(req.Context(), subscriptionIDParam, 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).EnabledSubscriptionID, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (s *ServerTransport) dispatchRename(req *http.Request) (*http.Response, error) {
	if s.srv.Rename == nil {
		return nil, &nonRetriableError{errors.New("fake for method Rename not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Subscription/rename`
	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[armsubscription.Name](req)
	if err != nil {
		return nil, err
	}
	subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.Rename(req.Context(), subscriptionIDParam, body, 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).RenamedSubscriptionID, 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)
}
