//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/reservations/armreservations/v3"
	"net/http"
	"net/url"
	"regexp"
)

// ReservationOrderServer is a fake server for instances of the armreservations.ReservationOrderClient type.
type ReservationOrderServer struct {
	// Calculate is the fake for method ReservationOrderClient.Calculate
	// HTTP status codes to indicate success: http.StatusOK
	Calculate func(ctx context.Context, body armreservations.PurchaseRequest, options *armreservations.ReservationOrderClientCalculateOptions) (resp azfake.Responder[armreservations.ReservationOrderClientCalculateResponse], errResp azfake.ErrorResponder)

	// ChangeDirectory is the fake for method ReservationOrderClient.ChangeDirectory
	// HTTP status codes to indicate success: http.StatusOK
	ChangeDirectory func(ctx context.Context, reservationOrderID string, body armreservations.ChangeDirectoryRequest, options *armreservations.ReservationOrderClientChangeDirectoryOptions) (resp azfake.Responder[armreservations.ReservationOrderClientChangeDirectoryResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method ReservationOrderClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, reservationOrderID string, options *armreservations.ReservationOrderClientGetOptions) (resp azfake.Responder[armreservations.ReservationOrderClientGetResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method ReservationOrderClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(options *armreservations.ReservationOrderClientListOptions) (resp azfake.PagerResponder[armreservations.ReservationOrderClientListResponse])

	// BeginPurchase is the fake for method ReservationOrderClient.BeginPurchase
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginPurchase func(ctx context.Context, reservationOrderID string, body armreservations.PurchaseRequest, options *armreservations.ReservationOrderClientBeginPurchaseOptions) (resp azfake.PollerResponder[armreservations.ReservationOrderClientPurchaseResponse], errResp azfake.ErrorResponder)
}

// NewReservationOrderServerTransport creates a new instance of ReservationOrderServerTransport with the provided implementation.
// The returned ReservationOrderServerTransport instance is connected to an instance of armreservations.ReservationOrderClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewReservationOrderServerTransport(srv *ReservationOrderServer) *ReservationOrderServerTransport {
	return &ReservationOrderServerTransport{
		srv:           srv,
		newListPager:  newTracker[azfake.PagerResponder[armreservations.ReservationOrderClientListResponse]](),
		beginPurchase: newTracker[azfake.PollerResponder[armreservations.ReservationOrderClientPurchaseResponse]](),
	}
}

// ReservationOrderServerTransport connects instances of armreservations.ReservationOrderClient to instances of ReservationOrderServer.
// Don't use this type directly, use NewReservationOrderServerTransport instead.
type ReservationOrderServerTransport struct {
	srv           *ReservationOrderServer
	newListPager  *tracker[azfake.PagerResponder[armreservations.ReservationOrderClientListResponse]]
	beginPurchase *tracker[azfake.PollerResponder[armreservations.ReservationOrderClientPurchaseResponse]]
}

// Do implements the policy.Transporter interface for ReservationOrderServerTransport.
func (r *ReservationOrderServerTransport) 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 "ReservationOrderClient.Calculate":
		resp, err = r.dispatchCalculate(req)
	case "ReservationOrderClient.ChangeDirectory":
		resp, err = r.dispatchChangeDirectory(req)
	case "ReservationOrderClient.Get":
		resp, err = r.dispatchGet(req)
	case "ReservationOrderClient.NewListPager":
		resp, err = r.dispatchNewListPager(req)
	case "ReservationOrderClient.BeginPurchase":
		resp, err = r.dispatchBeginPurchase(req)
	default:
		err = fmt.Errorf("unhandled API %s", method)
	}

	if err != nil {
		return nil, err
	}

	return resp, nil
}

func (r *ReservationOrderServerTransport) dispatchCalculate(req *http.Request) (*http.Response, error) {
	if r.srv.Calculate == nil {
		return nil, &nonRetriableError{errors.New("fake for method Calculate not implemented")}
	}
	body, err := server.UnmarshalRequestAsJSON[armreservations.PurchaseRequest](req)
	if err != nil {
		return nil, err
	}
	respr, errRespr := r.srv.Calculate(req.Context(), 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).CalculatePriceResponse, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (r *ReservationOrderServerTransport) dispatchChangeDirectory(req *http.Request) (*http.Response, error) {
	if r.srv.ChangeDirectory == nil {
		return nil, &nonRetriableError{errors.New("fake for method ChangeDirectory not implemented")}
	}
	const regexStr = `/providers/Microsoft\.Capacity/reservationOrders/(?P<reservationOrderId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/changeDirectory`
	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)
	}
	body, err := server.UnmarshalRequestAsJSON[armreservations.ChangeDirectoryRequest](req)
	if err != nil {
		return nil, err
	}
	reservationOrderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("reservationOrderId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := r.srv.ChangeDirectory(req.Context(), reservationOrderIDParam, 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).ChangeDirectoryResponse, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (r *ReservationOrderServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if r.srv.Get == nil {
		return nil, &nonRetriableError{errors.New("fake for method Get not implemented")}
	}
	const regexStr = `/providers/Microsoft\.Capacity/reservationOrders/(?P<reservationOrderId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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)
	}
	qp := req.URL.Query()
	reservationOrderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("reservationOrderId")])
	if err != nil {
		return nil, err
	}
	expandUnescaped, err := url.QueryUnescape(qp.Get("$expand"))
	if err != nil {
		return nil, err
	}
	expandParam := getOptional(expandUnescaped)
	var options *armreservations.ReservationOrderClientGetOptions
	if expandParam != nil {
		options = &armreservations.ReservationOrderClientGetOptions{
			Expand: expandParam,
		}
	}
	respr, errRespr := r.srv.Get(req.Context(), reservationOrderIDParam, 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).ReservationOrderResponse, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (r *ReservationOrderServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if r.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := r.newListPager.get(req)
	if newListPager == nil {
		resp := r.srv.NewListPager(nil)
		newListPager = &resp
		r.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armreservations.ReservationOrderClientListResponse, 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) {
		r.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		r.newListPager.remove(req)
	}
	return resp, nil
}

func (r *ReservationOrderServerTransport) dispatchBeginPurchase(req *http.Request) (*http.Response, error) {
	if r.srv.BeginPurchase == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginPurchase not implemented")}
	}
	beginPurchase := r.beginPurchase.get(req)
	if beginPurchase == nil {
		const regexStr = `/providers/Microsoft\.Capacity/reservationOrders/(?P<reservationOrderId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		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)
		}
		body, err := server.UnmarshalRequestAsJSON[armreservations.PurchaseRequest](req)
		if err != nil {
			return nil, err
		}
		reservationOrderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("reservationOrderId")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := r.srv.BeginPurchase(req.Context(), reservationOrderIDParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginPurchase = &respr
		r.beginPurchase.add(req, beginPurchase)
	}

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

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

	return resp, nil
}
