// 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/iotoperations/armiotoperations"
	"net/http"
	"net/url"
	"regexp"
	"slices"
)

// AkriServiceServer is a fake server for instances of the armiotoperations.AkriServiceClient type.
type AkriServiceServer struct {
	// BeginCreateOrUpdate is the fake for method AkriServiceClient.BeginCreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, instanceName string, akriServiceName string, resource armiotoperations.AkriServiceResource, options *armiotoperations.AkriServiceClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armiotoperations.AkriServiceClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method AkriServiceClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, instanceName string, akriServiceName string, options *armiotoperations.AkriServiceClientBeginDeleteOptions) (resp azfake.PollerResponder[armiotoperations.AkriServiceClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method AkriServiceClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, instanceName string, akriServiceName string, options *armiotoperations.AkriServiceClientGetOptions) (resp azfake.Responder[armiotoperations.AkriServiceClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByInstanceResourcePager is the fake for method AkriServiceClient.NewListByInstanceResourcePager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByInstanceResourcePager func(resourceGroupName string, instanceName string, options *armiotoperations.AkriServiceClientListByInstanceResourceOptions) (resp azfake.PagerResponder[armiotoperations.AkriServiceClientListByInstanceResourceResponse])
}

// NewAkriServiceServerTransport creates a new instance of AkriServiceServerTransport with the provided implementation.
// The returned AkriServiceServerTransport instance is connected to an instance of armiotoperations.AkriServiceClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewAkriServiceServerTransport(srv *AkriServiceServer) *AkriServiceServerTransport {
	return &AkriServiceServerTransport{
		srv:                            srv,
		beginCreateOrUpdate:            newTracker[azfake.PollerResponder[armiotoperations.AkriServiceClientCreateOrUpdateResponse]](),
		beginDelete:                    newTracker[azfake.PollerResponder[armiotoperations.AkriServiceClientDeleteResponse]](),
		newListByInstanceResourcePager: newTracker[azfake.PagerResponder[armiotoperations.AkriServiceClientListByInstanceResourceResponse]](),
	}
}

// AkriServiceServerTransport connects instances of armiotoperations.AkriServiceClient to instances of AkriServiceServer.
// Don't use this type directly, use NewAkriServiceServerTransport instead.
type AkriServiceServerTransport struct {
	srv                            *AkriServiceServer
	beginCreateOrUpdate            *tracker[azfake.PollerResponder[armiotoperations.AkriServiceClientCreateOrUpdateResponse]]
	beginDelete                    *tracker[azfake.PollerResponder[armiotoperations.AkriServiceClientDeleteResponse]]
	newListByInstanceResourcePager *tracker[azfake.PagerResponder[armiotoperations.AkriServiceClientListByInstanceResourceResponse]]
}

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

func (a *AkriServiceServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if akriServiceServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = akriServiceServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "AkriServiceClient.BeginCreateOrUpdate":
				res.resp, res.err = a.dispatchBeginCreateOrUpdate(req)
			case "AkriServiceClient.BeginDelete":
				res.resp, res.err = a.dispatchBeginDelete(req)
			case "AkriServiceClient.Get":
				res.resp, res.err = a.dispatchGet(req)
			case "AkriServiceClient.NewListByInstanceResourcePager":
				res.resp, res.err = a.dispatchNewListByInstanceResourcePager(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 (a *AkriServiceServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if a.srv.BeginCreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")}
	}
	beginCreateOrUpdate := a.beginCreateOrUpdate.get(req)
	if beginCreateOrUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.IoTOperations/instances/(?P<instanceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/akriServices/(?P<akriServiceName>[!#&$-;=?-\[\]_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[armiotoperations.AkriServiceResource](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		instanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("instanceName")])
		if err != nil {
			return nil, err
		}
		akriServiceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("akriServiceName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := a.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, instanceNameParam, akriServiceNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateOrUpdate = &respr
		a.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) {
		a.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) {
		a.beginCreateOrUpdate.remove(req)
	}

	return resp, nil
}

func (a *AkriServiceServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if a.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := a.beginDelete.get(req)
	if beginDelete == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.IoTOperations/instances/(?P<instanceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/akriServices/(?P<akriServiceName>[!#&$-;=?-\[\]_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
		}
		instanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("instanceName")])
		if err != nil {
			return nil, err
		}
		akriServiceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("akriServiceName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := a.srv.BeginDelete(req.Context(), resourceGroupNameParam, instanceNameParam, akriServiceNameParam, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		a.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) {
		a.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) {
		a.beginDelete.remove(req)
	}

	return resp, nil
}

func (a *AkriServiceServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if a.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\.IoTOperations/instances/(?P<instanceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/akriServices/(?P<akriServiceName>[!#&$-;=?-\[\]_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
	}
	instanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("instanceName")])
	if err != nil {
		return nil, err
	}
	akriServiceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("akriServiceName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, instanceNameParam, akriServiceNameParam, 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).AkriServiceResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *AkriServiceServerTransport) dispatchNewListByInstanceResourcePager(req *http.Request) (*http.Response, error) {
	if a.srv.NewListByInstanceResourcePager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByInstanceResourcePager not implemented")}
	}
	newListByInstanceResourcePager := a.newListByInstanceResourcePager.get(req)
	if newListByInstanceResourcePager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.IoTOperations/instances/(?P<instanceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/akriServices`
		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)
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		instanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("instanceName")])
		if err != nil {
			return nil, err
		}
		resp := a.srv.NewListByInstanceResourcePager(resourceGroupNameParam, instanceNameParam, nil)
		newListByInstanceResourcePager = &resp
		a.newListByInstanceResourcePager.add(req, newListByInstanceResourcePager)
		server.PagerResponderInjectNextLinks(newListByInstanceResourcePager, req, func(page *armiotoperations.AkriServiceClientListByInstanceResourceResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByInstanceResourcePager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		a.newListByInstanceResourcePager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByInstanceResourcePager) {
		a.newListByInstanceResourcePager.remove(req)
	}
	return resp, nil
}

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