// 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/resiliencemanagement/armresiliencemanagement"
	"net/http"
	"net/url"
	"regexp"
	"slices"
	"strconv"
)

// DrillResourcesServer is a fake server for instances of the armresiliencemanagement.DrillResourcesClient type.
type DrillResourcesServer struct {
	// Get is the fake for method DrillResourcesClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, serviceGroupName string, drillName string, drillResourceName string, options *armresiliencemanagement.DrillResourcesClientGetOptions) (resp azfake.Responder[armresiliencemanagement.DrillResourcesClientGetResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method DrillResourcesClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(serviceGroupName string, drillName string, options *armresiliencemanagement.DrillResourcesClientListOptions) (resp azfake.PagerResponder[armresiliencemanagement.DrillResourcesClientListResponse])
}

// NewDrillResourcesServerTransport creates a new instance of DrillResourcesServerTransport with the provided implementation.
// The returned DrillResourcesServerTransport instance is connected to an instance of armresiliencemanagement.DrillResourcesClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewDrillResourcesServerTransport(srv *DrillResourcesServer) *DrillResourcesServerTransport {
	return &DrillResourcesServerTransport{
		srv:          srv,
		newListPager: newTracker[azfake.PagerResponder[armresiliencemanagement.DrillResourcesClientListResponse]](),
	}
}

// DrillResourcesServerTransport connects instances of armresiliencemanagement.DrillResourcesClient to instances of DrillResourcesServer.
// Don't use this type directly, use NewDrillResourcesServerTransport instead.
type DrillResourcesServerTransport struct {
	srv          *DrillResourcesServer
	newListPager *tracker[azfake.PagerResponder[armresiliencemanagement.DrillResourcesClientListResponse]]
}

// Do implements the policy.Transporter interface for DrillResourcesServerTransport.
func (d *DrillResourcesServerTransport) 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 *DrillResourcesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if drillResourcesServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = drillResourcesServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "DrillResourcesClient.Get":
				res.resp, res.err = d.dispatchGet(req)
			case "DrillResourcesClient.NewListPager":
				res.resp, res.err = d.dispatchNewListPager(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 (d *DrillResourcesServerTransport) 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 = `/providers/Microsoft\.Management/serviceGroups/(?P<serviceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureResilienceManagement/drills/(?P<drillName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/drillResources/(?P<drillResourceName>[!#&$-;=?-\[\]_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)
	}
	serviceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceGroupName")])
	if err != nil {
		return nil, err
	}
	drillNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("drillName")])
	if err != nil {
		return nil, err
	}
	drillResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("drillResourceName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := d.srv.Get(req.Context(), serviceGroupNameParam, drillNameParam, drillResourceNameParam, 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).DrillResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (d *DrillResourcesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if d.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := d.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/providers/Microsoft\.Management/serviceGroups/(?P<serviceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureResilienceManagement/drills/(?P<drillName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/drillResources`
		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)
		}
		qp := req.URL.Query()
		serviceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceGroupName")])
		if err != nil {
			return nil, err
		}
		skipTokenParam := getOptional(qp.Get("$skipToken"))
		topParam, err := parseOptional(qp.Get("$top"), func(v string) (int32, error) {
			p, parseErr := strconv.ParseInt(v, 10, 32)
			if parseErr != nil {
				return 0, parseErr
			}
			return int32(p), nil
		})
		if err != nil {
			return nil, err
		}
		drillNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("drillName")])
		if err != nil {
			return nil, err
		}
		var options *armresiliencemanagement.DrillResourcesClientListOptions
		if skipTokenParam != nil || topParam != nil {
			options = &armresiliencemanagement.DrillResourcesClientListOptions{
				SkipToken: skipTokenParam,
				Top:       topParam,
			}
		}
		resp := d.srv.NewListPager(serviceGroupNameParam, drillNameParam, options)
		newListPager = &resp
		d.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armresiliencemanagement.DrillResourcesClientListResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		d.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		d.newListPager.remove(req)
	}
	return resp, nil
}

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