//go:build go1.18
// +build go1.18

// 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) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

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/billingbenefits/armbillingbenefits/v2"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
)

// SavingsPlanServer is a fake server for instances of the armbillingbenefits.SavingsPlanClient type.
type SavingsPlanServer struct {
	// Get is the fake for method SavingsPlanClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, savingsPlanOrderID string, savingsPlanID string, options *armbillingbenefits.SavingsPlanClientGetOptions) (resp azfake.Responder[armbillingbenefits.SavingsPlanClientGetResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method SavingsPlanClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(savingsPlanOrderID string, options *armbillingbenefits.SavingsPlanClientListOptions) (resp azfake.PagerResponder[armbillingbenefits.SavingsPlanClientListResponse])

	// NewListAllPager is the fake for method SavingsPlanClient.NewListAllPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListAllPager func(options *armbillingbenefits.SavingsPlanClientListAllOptions) (resp azfake.PagerResponder[armbillingbenefits.SavingsPlanClientListAllResponse])

	// Update is the fake for method SavingsPlanClient.Update
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	Update func(ctx context.Context, savingsPlanOrderID string, savingsPlanID string, body armbillingbenefits.SavingsPlanUpdateRequest, options *armbillingbenefits.SavingsPlanClientUpdateOptions) (resp azfake.Responder[armbillingbenefits.SavingsPlanClientUpdateResponse], errResp azfake.ErrorResponder)

	// ValidateUpdate is the fake for method SavingsPlanClient.ValidateUpdate
	// HTTP status codes to indicate success: http.StatusOK
	ValidateUpdate func(ctx context.Context, savingsPlanOrderID string, savingsPlanID string, body armbillingbenefits.SavingsPlanUpdateValidateRequest, options *armbillingbenefits.SavingsPlanClientValidateUpdateOptions) (resp azfake.Responder[armbillingbenefits.SavingsPlanClientValidateUpdateResponse], errResp azfake.ErrorResponder)
}

// NewSavingsPlanServerTransport creates a new instance of SavingsPlanServerTransport with the provided implementation.
// The returned SavingsPlanServerTransport instance is connected to an instance of armbillingbenefits.SavingsPlanClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewSavingsPlanServerTransport(srv *SavingsPlanServer) *SavingsPlanServerTransport {
	return &SavingsPlanServerTransport{
		srv:             srv,
		newListPager:    newTracker[azfake.PagerResponder[armbillingbenefits.SavingsPlanClientListResponse]](),
		newListAllPager: newTracker[azfake.PagerResponder[armbillingbenefits.SavingsPlanClientListAllResponse]](),
	}
}

// SavingsPlanServerTransport connects instances of armbillingbenefits.SavingsPlanClient to instances of SavingsPlanServer.
// Don't use this type directly, use NewSavingsPlanServerTransport instead.
type SavingsPlanServerTransport struct {
	srv             *SavingsPlanServer
	newListPager    *tracker[azfake.PagerResponder[armbillingbenefits.SavingsPlanClientListResponse]]
	newListAllPager *tracker[azfake.PagerResponder[armbillingbenefits.SavingsPlanClientListAllResponse]]
}

// Do implements the policy.Transporter interface for SavingsPlanServerTransport.
func (s *SavingsPlanServerTransport) 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")}
	}

	var resp *http.Response
	var err error

	switch method {
	case "SavingsPlanClient.Get":
		resp, err = s.dispatchGet(req)
	case "SavingsPlanClient.NewListPager":
		resp, err = s.dispatchNewListPager(req)
	case "SavingsPlanClient.NewListAllPager":
		resp, err = s.dispatchNewListAllPager(req)
	case "SavingsPlanClient.Update":
		resp, err = s.dispatchUpdate(req)
	case "SavingsPlanClient.ValidateUpdate":
		resp, err = s.dispatchValidateUpdate(req)
	default:
		err = fmt.Errorf("unhandled API %s", method)
	}

	if err != nil {
		return nil, err
	}

	return resp, nil
}

func (s *SavingsPlanServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if s.srv.Get == nil {
		return nil, &nonRetriableError{errors.New("fake for method Get not implemented")}
	}
	const regexStr = `/providers/Microsoft\.BillingBenefits/savingsPlanOrders/(?P<savingsPlanOrderId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/savingsPlans/(?P<savingsPlanId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 2 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	qp := req.URL.Query()
	savingsPlanOrderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanOrderId")])
	if err != nil {
		return nil, err
	}
	savingsPlanIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanId")])
	if err != nil {
		return nil, err
	}
	expandUnescaped, err := url.QueryUnescape(qp.Get("$expand"))
	if err != nil {
		return nil, err
	}
	expandParam := getOptional(expandUnescaped)
	var options *armbillingbenefits.SavingsPlanClientGetOptions
	if expandParam != nil {
		options = &armbillingbenefits.SavingsPlanClientGetOptions{
			Expand: expandParam,
		}
	}
	respr, errRespr := s.srv.Get(req.Context(), savingsPlanOrderIDParam, savingsPlanIDParam, options)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !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).SavingsPlanModel, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (s *SavingsPlanServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if s.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := s.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/providers/Microsoft\.BillingBenefits/savingsPlanOrders/(?P<savingsPlanOrderId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/savingsPlans`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 1 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		savingsPlanOrderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanOrderId")])
		if err != nil {
			return nil, err
		}
		resp := s.srv.NewListPager(savingsPlanOrderIDParam, nil)
		newListPager = &resp
		s.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armbillingbenefits.SavingsPlanClientListResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		s.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		s.newListPager.remove(req)
	}
	return resp, nil
}

func (s *SavingsPlanServerTransport) dispatchNewListAllPager(req *http.Request) (*http.Response, error) {
	if s.srv.NewListAllPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListAllPager not implemented")}
	}
	newListAllPager := s.newListAllPager.get(req)
	if newListAllPager == nil {
		qp := req.URL.Query()
		filterUnescaped, err := url.QueryUnescape(qp.Get("$filter"))
		if err != nil {
			return nil, err
		}
		filterParam := getOptional(filterUnescaped)
		orderbyUnescaped, err := url.QueryUnescape(qp.Get("$orderby"))
		if err != nil {
			return nil, err
		}
		orderbyParam := getOptional(orderbyUnescaped)
		refreshSummaryUnescaped, err := url.QueryUnescape(qp.Get("refreshSummary"))
		if err != nil {
			return nil, err
		}
		refreshSummaryParam := getOptional(refreshSummaryUnescaped)
		skiptokenUnescaped, err := url.QueryUnescape(qp.Get("$skiptoken"))
		if err != nil {
			return nil, err
		}
		skiptokenParam, err := parseOptional(skiptokenUnescaped, func(v string) (float32, error) {
			p, parseErr := strconv.ParseFloat(v, 32)
			if parseErr != nil {
				return 0, parseErr
			}
			return float32(p), nil
		})
		if err != nil {
			return nil, err
		}
		selectedStateUnescaped, err := url.QueryUnescape(qp.Get("selectedState"))
		if err != nil {
			return nil, err
		}
		selectedStateParam := getOptional(selectedStateUnescaped)
		takeUnescaped, err := url.QueryUnescape(qp.Get("take"))
		if err != nil {
			return nil, err
		}
		takeParam, err := parseOptional(takeUnescaped, func(v string) (float32, error) {
			p, parseErr := strconv.ParseFloat(v, 32)
			if parseErr != nil {
				return 0, parseErr
			}
			return float32(p), nil
		})
		if err != nil {
			return nil, err
		}
		var options *armbillingbenefits.SavingsPlanClientListAllOptions
		if filterParam != nil || orderbyParam != nil || refreshSummaryParam != nil || skiptokenParam != nil || selectedStateParam != nil || takeParam != nil {
			options = &armbillingbenefits.SavingsPlanClientListAllOptions{
				Filter:         filterParam,
				Orderby:        orderbyParam,
				RefreshSummary: refreshSummaryParam,
				Skiptoken:      skiptokenParam,
				SelectedState:  selectedStateParam,
				Take:           takeParam,
			}
		}
		resp := s.srv.NewListAllPager(options)
		newListAllPager = &resp
		s.newListAllPager.add(req, newListAllPager)
		server.PagerResponderInjectNextLinks(newListAllPager, req, func(page *armbillingbenefits.SavingsPlanClientListAllResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListAllPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		s.newListAllPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListAllPager) {
		s.newListAllPager.remove(req)
	}
	return resp, nil
}

func (s *SavingsPlanServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) {
	if s.srv.Update == nil {
		return nil, &nonRetriableError{errors.New("fake for method Update not implemented")}
	}
	const regexStr = `/providers/Microsoft\.BillingBenefits/savingsPlanOrders/(?P<savingsPlanOrderId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/savingsPlans/(?P<savingsPlanId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 2 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.SavingsPlanUpdateRequest](req)
	if err != nil {
		return nil, err
	}
	savingsPlanOrderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanOrderId")])
	if err != nil {
		return nil, err
	}
	savingsPlanIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.Update(req.Context(), savingsPlanOrderIDParam, savingsPlanIDParam, body, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK, http.StatusAccepted}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SavingsPlanModel, req)
	if err != nil {
		return nil, err
	}
	if val := server.GetResponse(respr).Location; val != nil {
		resp.Header.Set("Location", *val)
	}
	return resp, nil
}

func (s *SavingsPlanServerTransport) dispatchValidateUpdate(req *http.Request) (*http.Response, error) {
	if s.srv.ValidateUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method ValidateUpdate not implemented")}
	}
	const regexStr = `/providers/Microsoft\.BillingBenefits/savingsPlanOrders/(?P<savingsPlanOrderId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/savingsPlans/(?P<savingsPlanId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/validate`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 2 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.SavingsPlanUpdateValidateRequest](req)
	if err != nil {
		return nil, err
	}
	savingsPlanOrderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanOrderId")])
	if err != nil {
		return nil, err
	}
	savingsPlanIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.ValidateUpdate(req.Context(), savingsPlanOrderIDParam, savingsPlanIDParam, body, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !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).SavingsPlanValidateResponse, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}
