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

// ProviderRegistrationsServer is a fake server for instances of the armproviderhub.ProviderRegistrationsClient type.
type ProviderRegistrationsServer struct {
	// BeginCreateOrUpdate is the fake for method ProviderRegistrationsClient.BeginCreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	BeginCreateOrUpdate func(ctx context.Context, providerNamespace string, properties armproviderhub.ProviderRegistration, options *armproviderhub.ProviderRegistrationsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armproviderhub.ProviderRegistrationsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method ProviderRegistrationsClient.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, providerNamespace string, options *armproviderhub.ProviderRegistrationsClientDeleteOptions) (resp azfake.Responder[armproviderhub.ProviderRegistrationsClientDeleteResponse], errResp azfake.ErrorResponder)

	// GenerateOperations is the fake for method ProviderRegistrationsClient.GenerateOperations
	// HTTP status codes to indicate success: http.StatusOK
	GenerateOperations func(ctx context.Context, providerNamespace string, options *armproviderhub.ProviderRegistrationsClientGenerateOperationsOptions) (resp azfake.Responder[armproviderhub.ProviderRegistrationsClientGenerateOperationsResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method ProviderRegistrationsClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, providerNamespace string, options *armproviderhub.ProviderRegistrationsClientGetOptions) (resp azfake.Responder[armproviderhub.ProviderRegistrationsClientGetResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method ProviderRegistrationsClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(options *armproviderhub.ProviderRegistrationsClientListOptions) (resp azfake.PagerResponder[armproviderhub.ProviderRegistrationsClientListResponse])
}

// NewProviderRegistrationsServerTransport creates a new instance of ProviderRegistrationsServerTransport with the provided implementation.
// The returned ProviderRegistrationsServerTransport instance is connected to an instance of armproviderhub.ProviderRegistrationsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewProviderRegistrationsServerTransport(srv *ProviderRegistrationsServer) *ProviderRegistrationsServerTransport {
	return &ProviderRegistrationsServerTransport{
		srv:                 srv,
		beginCreateOrUpdate: newTracker[azfake.PollerResponder[armproviderhub.ProviderRegistrationsClientCreateOrUpdateResponse]](),
		newListPager:        newTracker[azfake.PagerResponder[armproviderhub.ProviderRegistrationsClientListResponse]](),
	}
}

// ProviderRegistrationsServerTransport connects instances of armproviderhub.ProviderRegistrationsClient to instances of ProviderRegistrationsServer.
// Don't use this type directly, use NewProviderRegistrationsServerTransport instead.
type ProviderRegistrationsServerTransport struct {
	srv                 *ProviderRegistrationsServer
	beginCreateOrUpdate *tracker[azfake.PollerResponder[armproviderhub.ProviderRegistrationsClientCreateOrUpdateResponse]]
	newListPager        *tracker[azfake.PagerResponder[armproviderhub.ProviderRegistrationsClientListResponse]]
}

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

func (p *ProviderRegistrationsServerTransport) 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 providerRegistrationsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = providerRegistrationsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "ProviderRegistrationsClient.BeginCreateOrUpdate":
				res.resp, res.err = p.dispatchBeginCreateOrUpdate(req)
			case "ProviderRegistrationsClient.Delete":
				res.resp, res.err = p.dispatchDelete(req)
			case "ProviderRegistrationsClient.GenerateOperations":
				res.resp, res.err = p.dispatchGenerateOperations(req)
			case "ProviderRegistrationsClient.Get":
				res.resp, res.err = p.dispatchGet(req)
			case "ProviderRegistrationsClient.NewListPager":
				res.resp, res.err = p.dispatchNewListPager(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 (p *ProviderRegistrationsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if p.srv.BeginCreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")}
	}
	beginCreateOrUpdate := p.beginCreateOrUpdate.get(req)
	if beginCreateOrUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ProviderHub/providerRegistrations/(?P<providerNamespace>[!#&$-;=?-\[\]_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[armproviderhub.ProviderRegistration](req)
		if err != nil {
			return nil, err
		}
		providerNamespaceParam, err := url.PathUnescape(matches[regex.SubexpIndex("providerNamespace")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := p.srv.BeginCreateOrUpdate(req.Context(), providerNamespaceParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateOrUpdate = &respr
		p.beginCreateOrUpdate.add(req, beginCreateOrUpdate)
	}

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

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

	return resp, nil
}

func (p *ProviderRegistrationsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if p.srv.Delete == nil {
		return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ProviderHub/providerRegistrations/(?P<providerNamespace>[!#&$-;=?-\[\]_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)
	}
	providerNamespaceParam, err := url.PathUnescape(matches[regex.SubexpIndex("providerNamespace")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := p.srv.Delete(req.Context(), providerNamespaceParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !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 (p *ProviderRegistrationsServerTransport) dispatchGenerateOperations(req *http.Request) (*http.Response, error) {
	if p.srv.GenerateOperations == nil {
		return nil, &nonRetriableError{errors.New("fake for method GenerateOperations not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ProviderHub/providerRegistrations/(?P<providerNamespace>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/generateOperations`
	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)
	}
	providerNamespaceParam, err := url.PathUnescape(matches[regex.SubexpIndex("providerNamespace")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := p.srv.GenerateOperations(req.Context(), providerNamespaceParam, 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).OperationsDefinitionArray, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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

func (p *ProviderRegistrationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if p.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := p.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ProviderHub/providerRegistrations`
		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)
		}
		resp := p.srv.NewListPager(nil)
		newListPager = &resp
		p.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armproviderhub.ProviderRegistrationsClientListResponse, 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) {
		p.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		p.newListPager.remove(req)
	}
	return resp, nil
}

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