// 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"
	"strconv"
)

// InvoiceSectionsServer is a fake server for instances of the armbilling.InvoiceSectionsClient type.
type InvoiceSectionsServer struct {
	// BeginCreateOrUpdate is the fake for method InvoiceSectionsClient.BeginCreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated, http.StatusAccepted
	BeginCreateOrUpdate func(ctx context.Context, billingAccountName string, billingProfileName string, invoiceSectionName string, parameters armbilling.InvoiceSection, options *armbilling.InvoiceSectionsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armbilling.InvoiceSectionsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method InvoiceSectionsClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, billingAccountName string, billingProfileName string, invoiceSectionName string, options *armbilling.InvoiceSectionsClientBeginDeleteOptions) (resp azfake.PollerResponder[armbilling.InvoiceSectionsClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method InvoiceSectionsClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, billingAccountName string, billingProfileName string, invoiceSectionName string, options *armbilling.InvoiceSectionsClientGetOptions) (resp azfake.Responder[armbilling.InvoiceSectionsClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByBillingProfilePager is the fake for method InvoiceSectionsClient.NewListByBillingProfilePager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByBillingProfilePager func(billingAccountName string, billingProfileName string, options *armbilling.InvoiceSectionsClientListByBillingProfileOptions) (resp azfake.PagerResponder[armbilling.InvoiceSectionsClientListByBillingProfileResponse])

	// ValidateDeleteEligibility is the fake for method InvoiceSectionsClient.ValidateDeleteEligibility
	// HTTP status codes to indicate success: http.StatusOK
	ValidateDeleteEligibility func(ctx context.Context, billingAccountName string, billingProfileName string, invoiceSectionName string, options *armbilling.InvoiceSectionsClientValidateDeleteEligibilityOptions) (resp azfake.Responder[armbilling.InvoiceSectionsClientValidateDeleteEligibilityResponse], errResp azfake.ErrorResponder)
}

// NewInvoiceSectionsServerTransport creates a new instance of InvoiceSectionsServerTransport with the provided implementation.
// The returned InvoiceSectionsServerTransport instance is connected to an instance of armbilling.InvoiceSectionsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewInvoiceSectionsServerTransport(srv *InvoiceSectionsServer) *InvoiceSectionsServerTransport {
	return &InvoiceSectionsServerTransport{
		srv:                          srv,
		beginCreateOrUpdate:          newTracker[azfake.PollerResponder[armbilling.InvoiceSectionsClientCreateOrUpdateResponse]](),
		beginDelete:                  newTracker[azfake.PollerResponder[armbilling.InvoiceSectionsClientDeleteResponse]](),
		newListByBillingProfilePager: newTracker[azfake.PagerResponder[armbilling.InvoiceSectionsClientListByBillingProfileResponse]](),
	}
}

// InvoiceSectionsServerTransport connects instances of armbilling.InvoiceSectionsClient to instances of InvoiceSectionsServer.
// Don't use this type directly, use NewInvoiceSectionsServerTransport instead.
type InvoiceSectionsServerTransport struct {
	srv                          *InvoiceSectionsServer
	beginCreateOrUpdate          *tracker[azfake.PollerResponder[armbilling.InvoiceSectionsClientCreateOrUpdateResponse]]
	beginDelete                  *tracker[azfake.PollerResponder[armbilling.InvoiceSectionsClientDeleteResponse]]
	newListByBillingProfilePager *tracker[azfake.PagerResponder[armbilling.InvoiceSectionsClientListByBillingProfileResponse]]
}

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

func (i *InvoiceSectionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if invoiceSectionsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = invoiceSectionsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "InvoiceSectionsClient.BeginCreateOrUpdate":
				res.resp, res.err = i.dispatchBeginCreateOrUpdate(req)
			case "InvoiceSectionsClient.BeginDelete":
				res.resp, res.err = i.dispatchBeginDelete(req)
			case "InvoiceSectionsClient.Get":
				res.resp, res.err = i.dispatchGet(req)
			case "InvoiceSectionsClient.NewListByBillingProfilePager":
				res.resp, res.err = i.dispatchNewListByBillingProfilePager(req)
			case "InvoiceSectionsClient.ValidateDeleteEligibility":
				res.resp, res.err = i.dispatchValidateDeleteEligibility(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 (i *InvoiceSectionsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if i.srv.BeginCreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")}
	}
	beginCreateOrUpdate := i.beginCreateOrUpdate.get(req)
	if beginCreateOrUpdate == nil {
		const regexStr = `/providers/Microsoft\.Billing/billingAccounts/(?P<billingAccountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/billingProfiles/(?P<billingProfileName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/invoiceSections/(?P<invoiceSectionName>[!#&$-;=?-\[\]_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[armbilling.InvoiceSection](req)
		if err != nil {
			return nil, err
		}
		billingAccountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingAccountName")])
		if err != nil {
			return nil, err
		}
		billingProfileNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingProfileName")])
		if err != nil {
			return nil, err
		}
		invoiceSectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("invoiceSectionName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := i.srv.BeginCreateOrUpdate(req.Context(), billingAccountNameParam, billingProfileNameParam, invoiceSectionNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateOrUpdate = &respr
		i.beginCreateOrUpdate.add(req, beginCreateOrUpdate)
	}

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

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

	return resp, nil
}

func (i *InvoiceSectionsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if i.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := i.beginDelete.get(req)
	if beginDelete == nil {
		const regexStr = `/providers/Microsoft\.Billing/billingAccounts/(?P<billingAccountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/billingProfiles/(?P<billingProfileName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/invoiceSections/(?P<invoiceSectionName>[!#&$-;=?-\[\]_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)
		}
		billingAccountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingAccountName")])
		if err != nil {
			return nil, err
		}
		billingProfileNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingProfileName")])
		if err != nil {
			return nil, err
		}
		invoiceSectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("invoiceSectionName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := i.srv.BeginDelete(req.Context(), billingAccountNameParam, billingProfileNameParam, invoiceSectionNameParam, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		i.beginDelete.add(req, beginDelete)
	}

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

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

	return resp, nil
}

func (i *InvoiceSectionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if i.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~%@]+)/billingProfiles/(?P<billingProfileName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/invoiceSections/(?P<invoiceSectionName>[!#&$-;=?-\[\]_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)
	}
	billingAccountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingAccountName")])
	if err != nil {
		return nil, err
	}
	billingProfileNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingProfileName")])
	if err != nil {
		return nil, err
	}
	invoiceSectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("invoiceSectionName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := i.srv.Get(req.Context(), billingAccountNameParam, billingProfileNameParam, invoiceSectionNameParam, 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).InvoiceSection, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (i *InvoiceSectionsServerTransport) dispatchNewListByBillingProfilePager(req *http.Request) (*http.Response, error) {
	if i.srv.NewListByBillingProfilePager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByBillingProfilePager not implemented")}
	}
	newListByBillingProfilePager := i.newListByBillingProfilePager.get(req)
	if newListByBillingProfilePager == nil {
		const regexStr = `/providers/Microsoft\.Billing/billingAccounts/(?P<billingAccountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/billingProfiles/(?P<billingProfileName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/invoiceSections`
		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()
		billingAccountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingAccountName")])
		if err != nil {
			return nil, err
		}
		billingProfileNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingProfileName")])
		if err != nil {
			return nil, err
		}
		includeDeletedParam, err := parseOptional(qp.Get("includeDeleted"), strconv.ParseBool)
		if err != nil {
			return nil, err
		}
		filterParam := getOptional(qp.Get("filter"))
		orderByParam := getOptional(qp.Get("orderBy"))
		topParam, err := parseOptional(qp.Get("top"), func(v string) (int64, error) {
			p, parseErr := strconv.ParseInt(v, 10, 64)
			if parseErr != nil {
				return 0, parseErr
			}
			return p, nil
		})
		if err != nil {
			return nil, err
		}
		skipParam, err := parseOptional(qp.Get("skip"), func(v string) (int64, error) {
			p, parseErr := strconv.ParseInt(v, 10, 64)
			if parseErr != nil {
				return 0, parseErr
			}
			return p, nil
		})
		if err != nil {
			return nil, err
		}
		countParam, err := parseOptional(qp.Get("count"), strconv.ParseBool)
		if err != nil {
			return nil, err
		}
		searchParam := getOptional(qp.Get("search"))
		var options *armbilling.InvoiceSectionsClientListByBillingProfileOptions
		if includeDeletedParam != nil || filterParam != nil || orderByParam != nil || topParam != nil || skipParam != nil || countParam != nil || searchParam != nil {
			options = &armbilling.InvoiceSectionsClientListByBillingProfileOptions{
				IncludeDeleted: includeDeletedParam,
				Filter:         filterParam,
				OrderBy:        orderByParam,
				Top:            topParam,
				Skip:           skipParam,
				Count:          countParam,
				Search:         searchParam,
			}
		}
		resp := i.srv.NewListByBillingProfilePager(billingAccountNameParam, billingProfileNameParam, options)
		newListByBillingProfilePager = &resp
		i.newListByBillingProfilePager.add(req, newListByBillingProfilePager)
		server.PagerResponderInjectNextLinks(newListByBillingProfilePager, req, func(page *armbilling.InvoiceSectionsClientListByBillingProfileResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByBillingProfilePager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		i.newListByBillingProfilePager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByBillingProfilePager) {
		i.newListByBillingProfilePager.remove(req)
	}
	return resp, nil
}

func (i *InvoiceSectionsServerTransport) dispatchValidateDeleteEligibility(req *http.Request) (*http.Response, error) {
	if i.srv.ValidateDeleteEligibility == nil {
		return nil, &nonRetriableError{errors.New("fake for method ValidateDeleteEligibility not implemented")}
	}
	const regexStr = `/providers/Microsoft\.Billing/billingAccounts/(?P<billingAccountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/billingProfiles/(?P<billingProfileName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/invoiceSections/(?P<invoiceSectionName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/validateDeleteEligibility`
	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)
	}
	billingAccountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingAccountName")])
	if err != nil {
		return nil, err
	}
	billingProfileNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingProfileName")])
	if err != nil {
		return nil, err
	}
	invoiceSectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("invoiceSectionName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := i.srv.ValidateDeleteEligibility(req.Context(), billingAccountNameParam, billingProfileNameParam, invoiceSectionNameParam, 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).DeleteInvoiceSectionEligibilityResult, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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