// 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/billing/armbilling/v2"
	"net/http"
	"net/url"
	"regexp"
	"slices"
)

// AgreementsServer is a fake server for instances of the armbilling.AgreementsClient type.
type AgreementsServer struct {
	// Get is the fake for method AgreementsClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, billingAccountName string, agreementName string, options *armbilling.AgreementsClientGetOptions) (resp azfake.Responder[armbilling.AgreementsClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByBillingAccountPager is the fake for method AgreementsClient.NewListByBillingAccountPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByBillingAccountPager func(billingAccountName string, options *armbilling.AgreementsClientListByBillingAccountOptions) (resp azfake.PagerResponder[armbilling.AgreementsClientListByBillingAccountResponse])
}

// NewAgreementsServerTransport creates a new instance of AgreementsServerTransport with the provided implementation.
// The returned AgreementsServerTransport instance is connected to an instance of armbilling.AgreementsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewAgreementsServerTransport(srv *AgreementsServer) *AgreementsServerTransport {
	return &AgreementsServerTransport{
		srv:                          srv,
		newListByBillingAccountPager: newTracker[azfake.PagerResponder[armbilling.AgreementsClientListByBillingAccountResponse]](),
	}
}

// AgreementsServerTransport connects instances of armbilling.AgreementsClient to instances of AgreementsServer.
// Don't use this type directly, use NewAgreementsServerTransport instead.
type AgreementsServerTransport struct {
	srv                          *AgreementsServer
	newListByBillingAccountPager *tracker[azfake.PagerResponder[armbilling.AgreementsClientListByBillingAccountResponse]]
}

// Do implements the policy.Transporter interface for AgreementsServerTransport.
func (a *AgreementsServerTransport) 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 *AgreementsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if agreementsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = agreementsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "AgreementsClient.Get":
				res.resp, res.err = a.dispatchGet(req)
			case "AgreementsClient.NewListByBillingAccountPager":
				res.resp, res.err = a.dispatchNewListByBillingAccountPager(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 *AgreementsServerTransport) 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 = `/providers/Microsoft\.Billing/billingAccounts/(?P<billingAccountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/agreements/(?P<agreementName>[!#&$-;=?-\[\]_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)
	}
	billingAccountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingAccountName")])
	if err != nil {
		return nil, err
	}
	agreementNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("agreementName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := a.srv.Get(req.Context(), billingAccountNameParam, agreementNameParam, 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).Agreement, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *AgreementsServerTransport) dispatchNewListByBillingAccountPager(req *http.Request) (*http.Response, error) {
	if a.srv.NewListByBillingAccountPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByBillingAccountPager not implemented")}
	}
	newListByBillingAccountPager := a.newListByBillingAccountPager.get(req)
	if newListByBillingAccountPager == nil {
		const regexStr = `/providers/Microsoft\.Billing/billingAccounts/(?P<billingAccountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/agreements`
		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()
		billingAccountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingAccountName")])
		if err != nil {
			return nil, err
		}
		expandParam := getOptional(qp.Get("expand"))
		var options *armbilling.AgreementsClientListByBillingAccountOptions
		if expandParam != nil {
			options = &armbilling.AgreementsClientListByBillingAccountOptions{
				Expand: expandParam,
			}
		}
		resp := a.srv.NewListByBillingAccountPager(billingAccountNameParam, options)
		newListByBillingAccountPager = &resp
		a.newListByBillingAccountPager.add(req, newListByBillingAccountPager)
		server.PagerResponderInjectNextLinks(newListByBillingAccountPager, req, func(page *armbilling.AgreementsClientListByBillingAccountResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByBillingAccountPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		a.newListByBillingAccountPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByBillingAccountPager) {
		a.newListByBillingAccountPager.remove(req)
	}
	return resp, nil
}

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