//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/managementgroups/armmanagementgroups"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
)

// Server is a fake server for instances of the armmanagementgroups.Client type.
type Server struct {
	// BeginCreateOrUpdate is the fake for method Client.BeginCreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginCreateOrUpdate func(ctx context.Context, groupID string, createManagementGroupRequest armmanagementgroups.CreateManagementGroupRequest, options *armmanagementgroups.ClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armmanagementgroups.ClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method Client.BeginDelete
	// HTTP status codes to indicate success: http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, groupID string, options *armmanagementgroups.ClientBeginDeleteOptions) (resp azfake.PollerResponder[armmanagementgroups.ClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method Client.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, groupID string, options *armmanagementgroups.ClientGetOptions) (resp azfake.Responder[armmanagementgroups.ClientGetResponse], errResp azfake.ErrorResponder)

	// NewGetDescendantsPager is the fake for method Client.NewGetDescendantsPager
	// HTTP status codes to indicate success: http.StatusOK
	NewGetDescendantsPager func(groupID string, options *armmanagementgroups.ClientGetDescendantsOptions) (resp azfake.PagerResponder[armmanagementgroups.ClientGetDescendantsResponse])

	// NewListPager is the fake for method Client.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(options *armmanagementgroups.ClientListOptions) (resp azfake.PagerResponder[armmanagementgroups.ClientListResponse])

	// Update is the fake for method Client.Update
	// HTTP status codes to indicate success: http.StatusOK
	Update func(ctx context.Context, groupID string, patchGroupRequest armmanagementgroups.PatchManagementGroupRequest, options *armmanagementgroups.ClientUpdateOptions) (resp azfake.Responder[armmanagementgroups.ClientUpdateResponse], errResp azfake.ErrorResponder)
}

// NewServerTransport creates a new instance of ServerTransport with the provided implementation.
// The returned ServerTransport instance is connected to an instance of armmanagementgroups.Client via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewServerTransport(srv *Server) *ServerTransport {
	return &ServerTransport{
		srv:                    srv,
		beginCreateOrUpdate:    newTracker[azfake.PollerResponder[armmanagementgroups.ClientCreateOrUpdateResponse]](),
		beginDelete:            newTracker[azfake.PollerResponder[armmanagementgroups.ClientDeleteResponse]](),
		newGetDescendantsPager: newTracker[azfake.PagerResponder[armmanagementgroups.ClientGetDescendantsResponse]](),
		newListPager:           newTracker[azfake.PagerResponder[armmanagementgroups.ClientListResponse]](),
	}
}

// ServerTransport connects instances of armmanagementgroups.Client to instances of Server.
// Don't use this type directly, use NewServerTransport instead.
type ServerTransport struct {
	srv                    *Server
	beginCreateOrUpdate    *tracker[azfake.PollerResponder[armmanagementgroups.ClientCreateOrUpdateResponse]]
	beginDelete            *tracker[azfake.PollerResponder[armmanagementgroups.ClientDeleteResponse]]
	newGetDescendantsPager *tracker[azfake.PagerResponder[armmanagementgroups.ClientGetDescendantsResponse]]
	newListPager           *tracker[azfake.PagerResponder[armmanagementgroups.ClientListResponse]]
}

// Do implements the policy.Transporter interface for ServerTransport.
func (s *ServerTransport) 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 "Client.BeginCreateOrUpdate":
		resp, err = s.dispatchBeginCreateOrUpdate(req)
	case "Client.BeginDelete":
		resp, err = s.dispatchBeginDelete(req)
	case "Client.Get":
		resp, err = s.dispatchGet(req)
	case "Client.NewGetDescendantsPager":
		resp, err = s.dispatchNewGetDescendantsPager(req)
	case "Client.NewListPager":
		resp, err = s.dispatchNewListPager(req)
	case "Client.Update":
		resp, err = s.dispatchUpdate(req)
	default:
		err = fmt.Errorf("unhandled API %s", method)
	}

	if err != nil {
		return nil, err
	}

	return resp, nil
}

func (s *ServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if s.srv.BeginCreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")}
	}
	beginCreateOrUpdate := s.beginCreateOrUpdate.get(req)
	if beginCreateOrUpdate == nil {
		const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P<groupId>[!#&$-;=?-\[\]_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[armmanagementgroups.CreateManagementGroupRequest](req)
		if err != nil {
			return nil, err
		}
		groupIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("groupId")])
		if err != nil {
			return nil, err
		}
		cacheControlParam := getOptional(getHeaderValue(req.Header, "Cache-Control"))
		var options *armmanagementgroups.ClientBeginCreateOrUpdateOptions
		if cacheControlParam != nil {
			options = &armmanagementgroups.ClientBeginCreateOrUpdateOptions{
				CacheControl: cacheControlParam,
			}
		}
		respr, errRespr := s.srv.BeginCreateOrUpdate(req.Context(), groupIDParam, body, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateOrUpdate = &respr
		s.beginCreateOrUpdate.add(req, beginCreateOrUpdate)
	}

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

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

	return resp, nil
}

func (s *ServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if s.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := s.beginDelete.get(req)
	if beginDelete == nil {
		const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P<groupId>[!#&$-;=?-\[\]_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)
		}
		groupIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("groupId")])
		if err != nil {
			return nil, err
		}
		cacheControlParam := getOptional(getHeaderValue(req.Header, "Cache-Control"))
		var options *armmanagementgroups.ClientBeginDeleteOptions
		if cacheControlParam != nil {
			options = &armmanagementgroups.ClientBeginDeleteOptions{
				CacheControl: cacheControlParam,
			}
		}
		respr, errRespr := s.srv.BeginDelete(req.Context(), groupIDParam, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		s.beginDelete.add(req, beginDelete)
	}

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

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

	return resp, nil
}

func (s *ServerTransport) 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\.Management/managementGroups/(?P<groupId>[!#&$-;=?-\[\]_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()
	groupIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("groupId")])
	if err != nil {
		return nil, err
	}
	expandUnescaped, err := url.QueryUnescape(qp.Get("$expand"))
	if err != nil {
		return nil, err
	}
	expandParam := getOptional(armmanagementgroups.ManagementGroupExpandType(expandUnescaped))
	recurseUnescaped, err := url.QueryUnescape(qp.Get("$recurse"))
	if err != nil {
		return nil, err
	}
	recurseParam, err := parseOptional(recurseUnescaped, strconv.ParseBool)
	if err != nil {
		return nil, err
	}
	filterUnescaped, err := url.QueryUnescape(qp.Get("$filter"))
	if err != nil {
		return nil, err
	}
	filterParam := getOptional(filterUnescaped)
	cacheControlParam := getOptional(getHeaderValue(req.Header, "Cache-Control"))
	var options *armmanagementgroups.ClientGetOptions
	if expandParam != nil || recurseParam != nil || filterParam != nil || cacheControlParam != nil {
		options = &armmanagementgroups.ClientGetOptions{
			Expand:       expandParam,
			Recurse:      recurseParam,
			Filter:       filterParam,
			CacheControl: cacheControlParam,
		}
	}
	respr, errRespr := s.srv.Get(req.Context(), groupIDParam, 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).ManagementGroup, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (s *ServerTransport) dispatchNewGetDescendantsPager(req *http.Request) (*http.Response, error) {
	if s.srv.NewGetDescendantsPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewGetDescendantsPager not implemented")}
	}
	newGetDescendantsPager := s.newGetDescendantsPager.get(req)
	if newGetDescendantsPager == nil {
		const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P<groupId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/descendants`
		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()
		groupIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("groupId")])
		if err != nil {
			return nil, err
		}
		skiptokenUnescaped, err := url.QueryUnescape(qp.Get("$skiptoken"))
		if err != nil {
			return nil, err
		}
		skiptokenParam := getOptional(skiptokenUnescaped)
		topUnescaped, err := url.QueryUnescape(qp.Get("$top"))
		if err != nil {
			return nil, err
		}
		topParam, err := parseOptional(topUnescaped, 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 *armmanagementgroups.ClientGetDescendantsOptions
		if skiptokenParam != nil || topParam != nil {
			options = &armmanagementgroups.ClientGetDescendantsOptions{
				Skiptoken: skiptokenParam,
				Top:       topParam,
			}
		}
		resp := s.srv.NewGetDescendantsPager(groupIDParam, options)
		newGetDescendantsPager = &resp
		s.newGetDescendantsPager.add(req, newGetDescendantsPager)
		server.PagerResponderInjectNextLinks(newGetDescendantsPager, req, func(page *armmanagementgroups.ClientGetDescendantsResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newGetDescendantsPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		s.newGetDescendantsPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newGetDescendantsPager) {
		s.newGetDescendantsPager.remove(req)
	}
	return resp, nil
}

func (s *ServerTransport) 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 {
		qp := req.URL.Query()
		cacheControlParam := getOptional(getHeaderValue(req.Header, "Cache-Control"))
		skiptokenUnescaped, err := url.QueryUnescape(qp.Get("$skiptoken"))
		if err != nil {
			return nil, err
		}
		skiptokenParam := getOptional(skiptokenUnescaped)
		var options *armmanagementgroups.ClientListOptions
		if cacheControlParam != nil || skiptokenParam != nil {
			options = &armmanagementgroups.ClientListOptions{
				CacheControl: cacheControlParam,
				Skiptoken:    skiptokenParam,
			}
		}
		resp := s.srv.NewListPager(options)
		newListPager = &resp
		s.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armmanagementgroups.ClientListResponse, 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 *ServerTransport) 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\.Management/managementGroups/(?P<groupId>[!#&$-;=?-\[\]_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[armmanagementgroups.PatchManagementGroupRequest](req)
	if err != nil {
		return nil, err
	}
	groupIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("groupId")])
	if err != nil {
		return nil, err
	}
	cacheControlParam := getOptional(getHeaderValue(req.Header, "Cache-Control"))
	var options *armmanagementgroups.ClientUpdateOptions
	if cacheControlParam != nil {
		options = &armmanagementgroups.ClientUpdateOptions{
			CacheControl: cacheControlParam,
		}
	}
	respr, errRespr := s.srv.Update(req.Context(), groupIDParam, body, 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).ManagementGroup, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}
