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

// DbNodesServer is a fake server for instances of the armoracledatabase.DbNodesClient type.
type DbNodesServer struct {
	// BeginAction is the fake for method DbNodesClient.BeginAction
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginAction func(ctx context.Context, resourceGroupName string, cloudvmclustername string, dbnodeocid string, body armoracledatabase.DbNodeAction, options *armoracledatabase.DbNodesClientBeginActionOptions) (resp azfake.PollerResponder[armoracledatabase.DbNodesClientActionResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method DbNodesClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, cloudvmclustername string, dbnodeocid string, options *armoracledatabase.DbNodesClientGetOptions) (resp azfake.Responder[armoracledatabase.DbNodesClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByCloudVMClusterPager is the fake for method DbNodesClient.NewListByCloudVMClusterPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByCloudVMClusterPager func(resourceGroupName string, cloudvmclustername string, options *armoracledatabase.DbNodesClientListByCloudVMClusterOptions) (resp azfake.PagerResponder[armoracledatabase.DbNodesClientListByCloudVMClusterResponse])
}

// NewDbNodesServerTransport creates a new instance of DbNodesServerTransport with the provided implementation.
// The returned DbNodesServerTransport instance is connected to an instance of armoracledatabase.DbNodesClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewDbNodesServerTransport(srv *DbNodesServer) *DbNodesServerTransport {
	return &DbNodesServerTransport{
		srv:                          srv,
		beginAction:                  newTracker[azfake.PollerResponder[armoracledatabase.DbNodesClientActionResponse]](),
		newListByCloudVMClusterPager: newTracker[azfake.PagerResponder[armoracledatabase.DbNodesClientListByCloudVMClusterResponse]](),
	}
}

// DbNodesServerTransport connects instances of armoracledatabase.DbNodesClient to instances of DbNodesServer.
// Don't use this type directly, use NewDbNodesServerTransport instead.
type DbNodesServerTransport struct {
	srv                          *DbNodesServer
	beginAction                  *tracker[azfake.PollerResponder[armoracledatabase.DbNodesClientActionResponse]]
	newListByCloudVMClusterPager *tracker[azfake.PagerResponder[armoracledatabase.DbNodesClientListByCloudVMClusterResponse]]
}

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

func (d *DbNodesServerTransport) 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 dbNodesServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = dbNodesServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "DbNodesClient.BeginAction":
				res.resp, res.err = d.dispatchBeginAction(req)
			case "DbNodesClient.Get":
				res.resp, res.err = d.dispatchGet(req)
			case "DbNodesClient.NewListByCloudVMClusterPager":
				res.resp, res.err = d.dispatchNewListByCloudVMClusterPager(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 (d *DbNodesServerTransport) dispatchBeginAction(req *http.Request) (*http.Response, error) {
	if d.srv.BeginAction == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginAction not implemented")}
	}
	beginAction := d.beginAction.get(req)
	if beginAction == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P<cloudvmclustername>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbNodes/(?P<dbnodeocid>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/action`
		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[armoracledatabase.DbNodeAction](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")])
		if err != nil {
			return nil, err
		}
		dbnodeocidParam, err := url.PathUnescape(matches[regex.SubexpIndex("dbnodeocid")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := d.srv.BeginAction(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, dbnodeocidParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginAction = &respr
		d.beginAction.add(req, beginAction)
	}

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

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

	return resp, nil
}

func (d *DbNodesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if d.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/Oracle\.Database/cloudVmClusters/(?P<cloudvmclustername>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbNodes/(?P<dbnodeocid>[!#&$-;=?-\[\]_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
	}
	cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")])
	if err != nil {
		return nil, err
	}
	dbnodeocidParam, err := url.PathUnescape(matches[regex.SubexpIndex("dbnodeocid")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, dbnodeocidParam, 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).DbNode, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (d *DbNodesServerTransport) dispatchNewListByCloudVMClusterPager(req *http.Request) (*http.Response, error) {
	if d.srv.NewListByCloudVMClusterPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByCloudVMClusterPager not implemented")}
	}
	newListByCloudVMClusterPager := d.newListByCloudVMClusterPager.get(req)
	if newListByCloudVMClusterPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P<cloudvmclustername>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbNodes`
		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
		}
		cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")])
		if err != nil {
			return nil, err
		}
		resp := d.srv.NewListByCloudVMClusterPager(resourceGroupNameParam, cloudvmclusternameParam, nil)
		newListByCloudVMClusterPager = &resp
		d.newListByCloudVMClusterPager.add(req, newListByCloudVMClusterPager)
		server.PagerResponderInjectNextLinks(newListByCloudVMClusterPager, req, func(page *armoracledatabase.DbNodesClientListByCloudVMClusterResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByCloudVMClusterPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		d.newListByCloudVMClusterPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByCloudVMClusterPager) {
		d.newListByCloudVMClusterPager.remove(req)
	}
	return resp, nil
}

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