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

// OffersServer is a fake server for instances of the armedgemarketplace.OffersClient type.
type OffersServer struct {
	// BeginGenerateAccessToken is the fake for method OffersClient.BeginGenerateAccessToken
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginGenerateAccessToken func(ctx context.Context, resourceURI string, offerID string, body armedgemarketplace.AccessTokenRequest, options *armedgemarketplace.OffersClientBeginGenerateAccessTokenOptions) (resp azfake.PollerResponder[armedgemarketplace.OffersClientGenerateAccessTokenResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method OffersClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceURI string, offerID string, options *armedgemarketplace.OffersClientGetOptions) (resp azfake.Responder[armedgemarketplace.OffersClientGetResponse], errResp azfake.ErrorResponder)

	// GetAccessToken is the fake for method OffersClient.GetAccessToken
	// HTTP status codes to indicate success: http.StatusOK
	GetAccessToken func(ctx context.Context, resourceURI string, offerID string, body armedgemarketplace.AccessTokenReadRequest, options *armedgemarketplace.OffersClientGetAccessTokenOptions) (resp azfake.Responder[armedgemarketplace.OffersClientGetAccessTokenResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method OffersClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(resourceURI string, options *armedgemarketplace.OffersClientListOptions) (resp azfake.PagerResponder[armedgemarketplace.OffersClientListResponse])

	// NewListBySubscriptionPager is the fake for method OffersClient.NewListBySubscriptionPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListBySubscriptionPager func(options *armedgemarketplace.OffersClientListBySubscriptionOptions) (resp azfake.PagerResponder[armedgemarketplace.OffersClientListBySubscriptionResponse])
}

// NewOffersServerTransport creates a new instance of OffersServerTransport with the provided implementation.
// The returned OffersServerTransport instance is connected to an instance of armedgemarketplace.OffersClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewOffersServerTransport(srv *OffersServer) *OffersServerTransport {
	return &OffersServerTransport{
		srv:                        srv,
		beginGenerateAccessToken:   newTracker[azfake.PollerResponder[armedgemarketplace.OffersClientGenerateAccessTokenResponse]](),
		newListPager:               newTracker[azfake.PagerResponder[armedgemarketplace.OffersClientListResponse]](),
		newListBySubscriptionPager: newTracker[azfake.PagerResponder[armedgemarketplace.OffersClientListBySubscriptionResponse]](),
	}
}

// OffersServerTransport connects instances of armedgemarketplace.OffersClient to instances of OffersServer.
// Don't use this type directly, use NewOffersServerTransport instead.
type OffersServerTransport struct {
	srv                        *OffersServer
	beginGenerateAccessToken   *tracker[azfake.PollerResponder[armedgemarketplace.OffersClientGenerateAccessTokenResponse]]
	newListPager               *tracker[azfake.PagerResponder[armedgemarketplace.OffersClientListResponse]]
	newListBySubscriptionPager *tracker[azfake.PagerResponder[armedgemarketplace.OffersClientListBySubscriptionResponse]]
}

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

func (o *OffersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if offersServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = offersServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "OffersClient.BeginGenerateAccessToken":
				res.resp, res.err = o.dispatchBeginGenerateAccessToken(req)
			case "OffersClient.Get":
				res.resp, res.err = o.dispatchGet(req)
			case "OffersClient.GetAccessToken":
				res.resp, res.err = o.dispatchGetAccessToken(req)
			case "OffersClient.NewListPager":
				res.resp, res.err = o.dispatchNewListPager(req)
			case "OffersClient.NewListBySubscriptionPager":
				res.resp, res.err = o.dispatchNewListBySubscriptionPager(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 (o *OffersServerTransport) dispatchBeginGenerateAccessToken(req *http.Request) (*http.Response, error) {
	if o.srv.BeginGenerateAccessToken == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginGenerateAccessToken not implemented")}
	}
	beginGenerateAccessToken := o.beginGenerateAccessToken.get(req)
	if beginGenerateAccessToken == nil {
		const regexStr = `/(?P<resourceUri>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.EdgeMarketplace/offers/(?P<offerId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/generateAccessToken`
		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)
		}
		body, err := server.UnmarshalRequestAsJSON[armedgemarketplace.AccessTokenRequest](req)
		if err != nil {
			return nil, err
		}
		resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")])
		if err != nil {
			return nil, err
		}
		offerIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("offerId")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := o.srv.BeginGenerateAccessToken(req.Context(), resourceURIParam, offerIDParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginGenerateAccessToken = &respr
		o.beginGenerateAccessToken.add(req, beginGenerateAccessToken)
	}

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

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

	return resp, nil
}

func (o *OffersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if o.srv.Get == nil {
		return nil, &nonRetriableError{errors.New("fake for method Get not implemented")}
	}
	const regexStr = `/(?P<resourceUri>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.EdgeMarketplace/offers/(?P<offerId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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)
	}
	resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")])
	if err != nil {
		return nil, err
	}
	offerIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("offerId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := o.srv.Get(req.Context(), resourceURIParam, offerIDParam, 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).Offer, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (o *OffersServerTransport) dispatchGetAccessToken(req *http.Request) (*http.Response, error) {
	if o.srv.GetAccessToken == nil {
		return nil, &nonRetriableError{errors.New("fake for method GetAccessToken not implemented")}
	}
	const regexStr = `/(?P<resourceUri>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.EdgeMarketplace/offers/(?P<offerId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/getAccessToken`
	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)
	}
	body, err := server.UnmarshalRequestAsJSON[armedgemarketplace.AccessTokenReadRequest](req)
	if err != nil {
		return nil, err
	}
	resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")])
	if err != nil {
		return nil, err
	}
	offerIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("offerId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := o.srv.GetAccessToken(req.Context(), resourceURIParam, offerIDParam, body, 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).DiskAccessToken, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (o *OffersServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if o.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := o.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/(?P<resourceUri>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.EdgeMarketplace/offers`
		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)
		}
		qp := req.URL.Query()
		resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")])
		if err != nil {
			return nil, err
		}
		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
		}
		skipParam, err := parseOptional(qp.Get("skip"), 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
		}
		maxpagesizeParam, err := parseOptional(qp.Get("maxpagesize"), 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
		}
		filterParam := getOptional(qp.Get("$filter"))
		skipTokenParam := getOptional(qp.Get("$skipToken"))
		var options *armedgemarketplace.OffersClientListOptions
		if topParam != nil || skipParam != nil || maxpagesizeParam != nil || filterParam != nil || skipTokenParam != nil {
			options = &armedgemarketplace.OffersClientListOptions{
				Top:         topParam,
				Skip:        skipParam,
				Maxpagesize: maxpagesizeParam,
				Filter:      filterParam,
				SkipToken:   skipTokenParam,
			}
		}
		resp := o.srv.NewListPager(resourceURIParam, options)
		newListPager = &resp
		o.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armedgemarketplace.OffersClientListResponse, 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) {
		o.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		o.newListPager.remove(req)
	}
	return resp, nil
}

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

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