// 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/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cloudhealth/armcloudhealth"
	"net/http"
	"net/url"
	"regexp"
	"slices"
	"time"
)

// RelationshipsServer is a fake server for instances of the armcloudhealth.RelationshipsClient type.
type RelationshipsServer struct {
	// BeginCreateOrUpdate is the fake for method RelationshipsClient.BeginCreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, resource armcloudhealth.Relationship, options *armcloudhealth.RelationshipsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcloudhealth.RelationshipsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method RelationshipsClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, options *armcloudhealth.RelationshipsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcloudhealth.RelationshipsClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method RelationshipsClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, options *armcloudhealth.RelationshipsClientGetOptions) (resp azfake.Responder[armcloudhealth.RelationshipsClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByHealthModelPager is the fake for method RelationshipsClient.NewListByHealthModelPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByHealthModelPager func(resourceGroupName string, healthModelName string, options *armcloudhealth.RelationshipsClientListByHealthModelOptions) (resp azfake.PagerResponder[armcloudhealth.RelationshipsClientListByHealthModelResponse])
}

// NewRelationshipsServerTransport creates a new instance of RelationshipsServerTransport with the provided implementation.
// The returned RelationshipsServerTransport instance is connected to an instance of armcloudhealth.RelationshipsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewRelationshipsServerTransport(srv *RelationshipsServer) *RelationshipsServerTransport {
	return &RelationshipsServerTransport{
		srv:                       srv,
		beginCreateOrUpdate:       newTracker[azfake.PollerResponder[armcloudhealth.RelationshipsClientCreateOrUpdateResponse]](),
		beginDelete:               newTracker[azfake.PollerResponder[armcloudhealth.RelationshipsClientDeleteResponse]](),
		newListByHealthModelPager: newTracker[azfake.PagerResponder[armcloudhealth.RelationshipsClientListByHealthModelResponse]](),
	}
}

// RelationshipsServerTransport connects instances of armcloudhealth.RelationshipsClient to instances of RelationshipsServer.
// Don't use this type directly, use NewRelationshipsServerTransport instead.
type RelationshipsServerTransport struct {
	srv                       *RelationshipsServer
	beginCreateOrUpdate       *tracker[azfake.PollerResponder[armcloudhealth.RelationshipsClientCreateOrUpdateResponse]]
	beginDelete               *tracker[azfake.PollerResponder[armcloudhealth.RelationshipsClientDeleteResponse]]
	newListByHealthModelPager *tracker[azfake.PagerResponder[armcloudhealth.RelationshipsClientListByHealthModelResponse]]
}

// Do implements the policy.Transporter interface for RelationshipsServerTransport.
func (r *RelationshipsServerTransport) 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 *RelationshipsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if relationshipsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = relationshipsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "RelationshipsClient.BeginCreateOrUpdate":
				res.resp, res.err = r.dispatchBeginCreateOrUpdate(req)
			case "RelationshipsClient.BeginDelete":
				res.resp, res.err = r.dispatchBeginDelete(req)
			case "RelationshipsClient.Get":
				res.resp, res.err = r.dispatchGet(req)
			case "RelationshipsClient.NewListByHealthModelPager":
				res.resp, res.err = r.dispatchNewListByHealthModelPager(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 *RelationshipsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if r.srv.BeginCreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")}
	}
	beginCreateOrUpdate := r.beginCreateOrUpdate.get(req)
	if beginCreateOrUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P<healthModelName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/relationships/(?P<relationshipName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 5 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		body, err := server.UnmarshalRequestAsJSON[armcloudhealth.Relationship](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")])
		if err != nil {
			return nil, err
		}
		relationshipNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("relationshipName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := r.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, healthModelNameParam, relationshipNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateOrUpdate = &respr
		r.beginCreateOrUpdate.add(req, beginCreateOrUpdate)
	}

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

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

	return resp, nil
}

func (r *RelationshipsServerTransport) 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\.CloudHealth/healthmodels/(?P<healthModelName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/relationships/(?P<relationshipName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 5 {
			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
		}
		healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")])
		if err != nil {
			return nil, err
		}
		relationshipNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("relationshipName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := r.srv.BeginDelete(req.Context(), resourceGroupNameParam, healthModelNameParam, relationshipNameParam, nil)
		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 *RelationshipsServerTransport) 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\.CloudHealth/healthmodels/(?P<healthModelName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/relationships/(?P<relationshipName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 5 {
		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
	}
	healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")])
	if err != nil {
		return nil, err
	}
	relationshipNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("relationshipName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := r.srv.Get(req.Context(), resourceGroupNameParam, healthModelNameParam, relationshipNameParam, 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).Relationship, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (r *RelationshipsServerTransport) dispatchNewListByHealthModelPager(req *http.Request) (*http.Response, error) {
	if r.srv.NewListByHealthModelPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByHealthModelPager not implemented")}
	}
	newListByHealthModelPager := r.newListByHealthModelPager.get(req)
	if newListByHealthModelPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P<healthModelName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/relationships`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 4 {
			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
		}
		timestampParam, err := parseOptional(qp.Get("timestamp"), func(v string) (time.Time, error) { return time.Parse(time.RFC3339Nano, v) })
		if err != nil {
			return nil, err
		}
		healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")])
		if err != nil {
			return nil, err
		}
		var options *armcloudhealth.RelationshipsClientListByHealthModelOptions
		if timestampParam != nil {
			options = &armcloudhealth.RelationshipsClientListByHealthModelOptions{
				Timestamp: timestampParam,
			}
		}
		resp := r.srv.NewListByHealthModelPager(resourceGroupNameParam, healthModelNameParam, options)
		newListByHealthModelPager = &resp
		r.newListByHealthModelPager.add(req, newListByHealthModelPager)
		server.PagerResponderInjectNextLinks(newListByHealthModelPager, req, func(page *armcloudhealth.RelationshipsClientListByHealthModelResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByHealthModelPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		r.newListByHealthModelPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByHealthModelPager) {
		r.newListByHealthModelPager.remove(req)
	}
	return resp, nil
}

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