// 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/containerservicefleet/armcontainerservicefleet/v3"
	"net/http"
	"net/url"
	"regexp"
)

// FleetsServer is a fake server for instances of the armcontainerservicefleet.FleetsClient type.
type FleetsServer struct {
	// BeginCreate is the fake for method FleetsClient.BeginCreate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	BeginCreate func(ctx context.Context, resourceGroupName string, fleetName string, resource armcontainerservicefleet.Fleet, options *armcontainerservicefleet.FleetsClientBeginCreateOptions) (resp azfake.PollerResponder[armcontainerservicefleet.FleetsClientCreateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method FleetsClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, fleetName string, options *armcontainerservicefleet.FleetsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcontainerservicefleet.FleetsClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method FleetsClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, fleetName string, options *armcontainerservicefleet.FleetsClientGetOptions) (resp azfake.Responder[armcontainerservicefleet.FleetsClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByResourceGroupPager is the fake for method FleetsClient.NewListByResourceGroupPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByResourceGroupPager func(resourceGroupName string, options *armcontainerservicefleet.FleetsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armcontainerservicefleet.FleetsClientListByResourceGroupResponse])

	// NewListBySubscriptionPager is the fake for method FleetsClient.NewListBySubscriptionPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListBySubscriptionPager func(options *armcontainerservicefleet.FleetsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armcontainerservicefleet.FleetsClientListBySubscriptionResponse])

	// ListCredentials is the fake for method FleetsClient.ListCredentials
	// HTTP status codes to indicate success: http.StatusOK
	ListCredentials func(ctx context.Context, resourceGroupName string, fleetName string, options *armcontainerservicefleet.FleetsClientListCredentialsOptions) (resp azfake.Responder[armcontainerservicefleet.FleetsClientListCredentialsResponse], errResp azfake.ErrorResponder)

	// BeginUpdateAsync is the fake for method FleetsClient.BeginUpdateAsync
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginUpdateAsync func(ctx context.Context, resourceGroupName string, fleetName string, properties armcontainerservicefleet.FleetPatch, options *armcontainerservicefleet.FleetsClientBeginUpdateAsyncOptions) (resp azfake.PollerResponder[armcontainerservicefleet.FleetsClientUpdateAsyncResponse], errResp azfake.ErrorResponder)
}

// NewFleetsServerTransport creates a new instance of FleetsServerTransport with the provided implementation.
// The returned FleetsServerTransport instance is connected to an instance of armcontainerservicefleet.FleetsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewFleetsServerTransport(srv *FleetsServer) *FleetsServerTransport {
	return &FleetsServerTransport{
		srv:                         srv,
		beginCreate:                 newTracker[azfake.PollerResponder[armcontainerservicefleet.FleetsClientCreateResponse]](),
		beginDelete:                 newTracker[azfake.PollerResponder[armcontainerservicefleet.FleetsClientDeleteResponse]](),
		newListByResourceGroupPager: newTracker[azfake.PagerResponder[armcontainerservicefleet.FleetsClientListByResourceGroupResponse]](),
		newListBySubscriptionPager:  newTracker[azfake.PagerResponder[armcontainerservicefleet.FleetsClientListBySubscriptionResponse]](),
		beginUpdateAsync:            newTracker[azfake.PollerResponder[armcontainerservicefleet.FleetsClientUpdateAsyncResponse]](),
	}
}

// FleetsServerTransport connects instances of armcontainerservicefleet.FleetsClient to instances of FleetsServer.
// Don't use this type directly, use NewFleetsServerTransport instead.
type FleetsServerTransport struct {
	srv                         *FleetsServer
	beginCreate                 *tracker[azfake.PollerResponder[armcontainerservicefleet.FleetsClientCreateResponse]]
	beginDelete                 *tracker[azfake.PollerResponder[armcontainerservicefleet.FleetsClientDeleteResponse]]
	newListByResourceGroupPager *tracker[azfake.PagerResponder[armcontainerservicefleet.FleetsClientListByResourceGroupResponse]]
	newListBySubscriptionPager  *tracker[azfake.PagerResponder[armcontainerservicefleet.FleetsClientListBySubscriptionResponse]]
	beginUpdateAsync            *tracker[azfake.PollerResponder[armcontainerservicefleet.FleetsClientUpdateAsyncResponse]]
}

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

func (f *FleetsServerTransport) 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 fleetsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = fleetsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "FleetsClient.BeginCreate":
				res.resp, res.err = f.dispatchBeginCreate(req)
			case "FleetsClient.BeginDelete":
				res.resp, res.err = f.dispatchBeginDelete(req)
			case "FleetsClient.Get":
				res.resp, res.err = f.dispatchGet(req)
			case "FleetsClient.NewListByResourceGroupPager":
				res.resp, res.err = f.dispatchNewListByResourceGroupPager(req)
			case "FleetsClient.NewListBySubscriptionPager":
				res.resp, res.err = f.dispatchNewListBySubscriptionPager(req)
			case "FleetsClient.ListCredentials":
				res.resp, res.err = f.dispatchListCredentials(req)
			case "FleetsClient.BeginUpdateAsync":
				res.resp, res.err = f.dispatchBeginUpdateAsync(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 (f *FleetsServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) {
	if f.srv.BeginCreate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")}
	}
	beginCreate := f.beginCreate.get(req)
	if beginCreate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ContainerService/fleets/(?P<fleetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		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)
		}
		body, err := server.UnmarshalRequestAsJSON[armcontainerservicefleet.Fleet](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
		ifNoneMatchParam := getOptional(getHeaderValue(req.Header, "If-None-Match"))
		fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")])
		if err != nil {
			return nil, err
		}
		var options *armcontainerservicefleet.FleetsClientBeginCreateOptions
		if ifMatchParam != nil || ifNoneMatchParam != nil {
			options = &armcontainerservicefleet.FleetsClientBeginCreateOptions{
				IfMatch:     ifMatchParam,
				IfNoneMatch: ifNoneMatchParam,
			}
		}
		respr, errRespr := f.srv.BeginCreate(req.Context(), resourceGroupNameParam, fleetNameParam, body, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreate = &respr
		f.beginCreate.add(req, beginCreate)
	}

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

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

	return resp, nil
}

func (f *FleetsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if f.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := f.beginDelete.get(req)
	if beginDelete == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ContainerService/fleets/(?P<fleetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		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
		}
		ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
		fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")])
		if err != nil {
			return nil, err
		}
		var options *armcontainerservicefleet.FleetsClientBeginDeleteOptions
		if ifMatchParam != nil {
			options = &armcontainerservicefleet.FleetsClientBeginDeleteOptions{
				IfMatch: ifMatchParam,
			}
		}
		respr, errRespr := f.srv.BeginDelete(req.Context(), resourceGroupNameParam, fleetNameParam, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		f.beginDelete.add(req, beginDelete)
	}

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

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

	return resp, nil
}

func (f *FleetsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if f.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\.ContainerService/fleets/(?P<fleetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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
	}
	fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := f.srv.Get(req.Context(), resourceGroupNameParam, fleetNameParam, 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).Fleet, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (f *FleetsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) {
	if f.srv.NewListByResourceGroupPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")}
	}
	newListByResourceGroupPager := f.newListByResourceGroupPager.get(req)
	if newListByResourceGroupPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ContainerService/fleets`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 3 {
			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
		}
		resp := f.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil)
		newListByResourceGroupPager = &resp
		f.newListByResourceGroupPager.add(req, newListByResourceGroupPager)
		server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armcontainerservicefleet.FleetsClientListByResourceGroupResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByResourceGroupPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		f.newListByResourceGroupPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByResourceGroupPager) {
		f.newListByResourceGroupPager.remove(req)
	}
	return resp, nil
}

func (f *FleetsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) {
	if f.srv.NewListBySubscriptionPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")}
	}
	newListBySubscriptionPager := f.newListBySubscriptionPager.get(req)
	if newListBySubscriptionPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ContainerService/fleets`
		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)
		}
		resp := f.srv.NewListBySubscriptionPager(nil)
		newListBySubscriptionPager = &resp
		f.newListBySubscriptionPager.add(req, newListBySubscriptionPager)
		server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armcontainerservicefleet.FleetsClientListBySubscriptionResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListBySubscriptionPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		f.newListBySubscriptionPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListBySubscriptionPager) {
		f.newListBySubscriptionPager.remove(req)
	}
	return resp, nil
}

func (f *FleetsServerTransport) dispatchListCredentials(req *http.Request) (*http.Response, error) {
	if f.srv.ListCredentials == nil {
		return nil, &nonRetriableError{errors.New("fake for method ListCredentials not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ContainerService/fleets/(?P<fleetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/listCredentials`
	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
	}
	fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := f.srv.ListCredentials(req.Context(), resourceGroupNameParam, fleetNameParam, 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).FleetCredentialResults, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (f *FleetsServerTransport) dispatchBeginUpdateAsync(req *http.Request) (*http.Response, error) {
	if f.srv.BeginUpdateAsync == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginUpdateAsync not implemented")}
	}
	beginUpdateAsync := f.beginUpdateAsync.get(req)
	if beginUpdateAsync == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ContainerService/fleets/(?P<fleetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		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)
		}
		body, err := server.UnmarshalRequestAsJSON[armcontainerservicefleet.FleetPatch](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
		fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")])
		if err != nil {
			return nil, err
		}
		var options *armcontainerservicefleet.FleetsClientBeginUpdateAsyncOptions
		if ifMatchParam != nil {
			options = &armcontainerservicefleet.FleetsClientBeginUpdateAsyncOptions{
				IfMatch: ifMatchParam,
			}
		}
		respr, errRespr := f.srv.BeginUpdateAsync(req.Context(), resourceGroupNameParam, fleetNameParam, body, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginUpdateAsync = &respr
		f.beginUpdateAsync.add(req, beginUpdateAsync)
	}

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

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

	return resp, nil
}

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