// 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/resourcemanager/consumption/armconsumption/v2"
	"net/http"
	"net/url"
	"regexp"
	"slices"
	"strconv"
)

// PriceSheetServer is a fake server for instances of the armconsumption.PriceSheetClient type.
type PriceSheetServer struct {
	// BeginDownloadByBillingAccountPeriod is the fake for method PriceSheetClient.BeginDownloadByBillingAccountPeriod
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginDownloadByBillingAccountPeriod func(ctx context.Context, billingAccountID string, billingPeriodName string, options *armconsumption.PriceSheetClientBeginDownloadByBillingAccountPeriodOptions) (resp azfake.PollerResponder[armconsumption.PriceSheetClientDownloadByBillingAccountPeriodResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method PriceSheetClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, options *armconsumption.PriceSheetClientGetOptions) (resp azfake.Responder[armconsumption.PriceSheetClientGetResponse], errResp azfake.ErrorResponder)

	// GetByBillingPeriod is the fake for method PriceSheetClient.GetByBillingPeriod
	// HTTP status codes to indicate success: http.StatusOK
	GetByBillingPeriod func(ctx context.Context, billingPeriodName string, options *armconsumption.PriceSheetClientGetByBillingPeriodOptions) (resp azfake.Responder[armconsumption.PriceSheetClientGetByBillingPeriodResponse], errResp azfake.ErrorResponder)
}

// NewPriceSheetServerTransport creates a new instance of PriceSheetServerTransport with the provided implementation.
// The returned PriceSheetServerTransport instance is connected to an instance of armconsumption.PriceSheetClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewPriceSheetServerTransport(srv *PriceSheetServer) *PriceSheetServerTransport {
	return &PriceSheetServerTransport{
		srv:                                 srv,
		beginDownloadByBillingAccountPeriod: newTracker[azfake.PollerResponder[armconsumption.PriceSheetClientDownloadByBillingAccountPeriodResponse]](),
	}
}

// PriceSheetServerTransport connects instances of armconsumption.PriceSheetClient to instances of PriceSheetServer.
// Don't use this type directly, use NewPriceSheetServerTransport instead.
type PriceSheetServerTransport struct {
	srv                                 *PriceSheetServer
	beginDownloadByBillingAccountPeriod *tracker[azfake.PollerResponder[armconsumption.PriceSheetClientDownloadByBillingAccountPeriodResponse]]
}

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

func (p *PriceSheetServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if priceSheetServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = priceSheetServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "PriceSheetClient.BeginDownloadByBillingAccountPeriod":
				res.resp, res.err = p.dispatchBeginDownloadByBillingAccountPeriod(req)
			case "PriceSheetClient.Get":
				res.resp, res.err = p.dispatchGet(req)
			case "PriceSheetClient.GetByBillingPeriod":
				res.resp, res.err = p.dispatchGetByBillingPeriod(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 (p *PriceSheetServerTransport) dispatchBeginDownloadByBillingAccountPeriod(req *http.Request) (*http.Response, error) {
	if p.srv.BeginDownloadByBillingAccountPeriod == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDownloadByBillingAccountPeriod not implemented")}
	}
	beginDownloadByBillingAccountPeriod := p.beginDownloadByBillingAccountPeriod.get(req)
	if beginDownloadByBillingAccountPeriod == nil {
		const regexStr = `/providers/Microsoft\.Billing/billingAccounts/(?P<billingAccountId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/billingPeriods/(?P<billingPeriodName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Consumption/pricesheets/download`
		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)
		}
		billingAccountIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingAccountId")])
		if err != nil {
			return nil, err
		}
		billingPeriodNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingPeriodName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := p.srv.BeginDownloadByBillingAccountPeriod(req.Context(), billingAccountIDParam, billingPeriodNameParam, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDownloadByBillingAccountPeriod = &respr
		p.beginDownloadByBillingAccountPeriod.add(req, beginDownloadByBillingAccountPeriod)
	}

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

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

	return resp, nil
}

func (p *PriceSheetServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if p.srv.Get == nil {
		return nil, &nonRetriableError{errors.New("fake for method Get not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Consumption/pricesheets/default`
	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()
	expandParam := getOptional(qp.Get("$expand"))
	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
	}
	var options *armconsumption.PriceSheetClientGetOptions
	if expandParam != nil || skiptokenParam != nil || topParam != nil {
		options = &armconsumption.PriceSheetClientGetOptions{
			Expand:    expandParam,
			Skiptoken: skiptokenParam,
			Top:       topParam,
		}
	}
	respr, errRespr := p.srv.Get(req.Context(), options)
	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).PriceSheetResult, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (p *PriceSheetServerTransport) dispatchGetByBillingPeriod(req *http.Request) (*http.Response, error) {
	if p.srv.GetByBillingPeriod == nil {
		return nil, &nonRetriableError{errors.New("fake for method GetByBillingPeriod not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Billing/billingPeriods/(?P<billingPeriodName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Consumption/pricesheets/default`
	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()
	billingPeriodNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingPeriodName")])
	if err != nil {
		return nil, err
	}
	expandParam := getOptional(qp.Get("$expand"))
	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
	}
	var options *armconsumption.PriceSheetClientGetByBillingPeriodOptions
	if expandParam != nil || skiptokenParam != nil || topParam != nil {
		options = &armconsumption.PriceSheetClientGetByBillingPeriodOptions{
			Expand:    expandParam,
			Skiptoken: skiptokenParam,
			Top:       topParam,
		}
	}
	respr, errRespr := p.srv.GetByBillingPeriod(req.Context(), billingPeriodNameParam, options)
	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).PriceSheetResult, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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