// 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/automation/armautomation"
	"net/http"
	"net/url"
	"regexp"
	"slices"
)

// PackageServer is a fake server for instances of the armautomation.PackageClient type.
type PackageServer struct {
	// CreateOrUpdate is the fake for method PackageClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrUpdate func(ctx context.Context, resourceGroupName string, automationAccountName string, runtimeEnvironmentName string, packageName string, parameters armautomation.PackageCreateOrUpdateParameters, options *armautomation.PackageClientCreateOrUpdateOptions) (resp azfake.Responder[armautomation.PackageClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method PackageClient.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, resourceGroupName string, automationAccountName string, runtimeEnvironmentName string, packageName string, options *armautomation.PackageClientDeleteOptions) (resp azfake.Responder[armautomation.PackageClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method PackageClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, automationAccountName string, runtimeEnvironmentName string, packageName string, options *armautomation.PackageClientGetOptions) (resp azfake.Responder[armautomation.PackageClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByRuntimeEnvironmentPager is the fake for method PackageClient.NewListByRuntimeEnvironmentPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByRuntimeEnvironmentPager func(resourceGroupName string, automationAccountName string, runtimeEnvironmentName string, options *armautomation.PackageClientListByRuntimeEnvironmentOptions) (resp azfake.PagerResponder[armautomation.PackageClientListByRuntimeEnvironmentResponse])

	// Update is the fake for method PackageClient.Update
	// HTTP status codes to indicate success: http.StatusOK
	Update func(ctx context.Context, resourceGroupName string, automationAccountName string, runtimeEnvironmentName string, packageName string, parameters armautomation.PackageUpdateParameters, options *armautomation.PackageClientUpdateOptions) (resp azfake.Responder[armautomation.PackageClientUpdateResponse], errResp azfake.ErrorResponder)
}

// NewPackageServerTransport creates a new instance of PackageServerTransport with the provided implementation.
// The returned PackageServerTransport instance is connected to an instance of armautomation.PackageClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewPackageServerTransport(srv *PackageServer) *PackageServerTransport {
	return &PackageServerTransport{
		srv:                              srv,
		newListByRuntimeEnvironmentPager: newTracker[azfake.PagerResponder[armautomation.PackageClientListByRuntimeEnvironmentResponse]](),
	}
}

// PackageServerTransport connects instances of armautomation.PackageClient to instances of PackageServer.
// Don't use this type directly, use NewPackageServerTransport instead.
type PackageServerTransport struct {
	srv                              *PackageServer
	newListByRuntimeEnvironmentPager *tracker[azfake.PagerResponder[armautomation.PackageClientListByRuntimeEnvironmentResponse]]
}

// Do implements the policy.Transporter interface for PackageServerTransport.
func (p *PackageServerTransport) 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 *PackageServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if packageServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = packageServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "PackageClient.CreateOrUpdate":
				res.resp, res.err = p.dispatchCreateOrUpdate(req)
			case "PackageClient.Delete":
				res.resp, res.err = p.dispatchDelete(req)
			case "PackageClient.Get":
				res.resp, res.err = p.dispatchGet(req)
			case "PackageClient.NewListByRuntimeEnvironmentPager":
				res.resp, res.err = p.dispatchNewListByRuntimeEnvironmentPager(req)
			case "PackageClient.Update":
				res.resp, res.err = p.dispatchUpdate(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 *PackageServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if p.srv.CreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Automation/automationAccounts/(?P<automationAccountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/runtimeEnvironments/(?P<runtimeEnvironmentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/packages/(?P<packageName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armautomation.PackageCreateOrUpdateParameters](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	automationAccountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("automationAccountName")])
	if err != nil {
		return nil, err
	}
	runtimeEnvironmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("runtimeEnvironmentName")])
	if err != nil {
		return nil, err
	}
	packageNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("packageName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := p.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, automationAccountNameParam, runtimeEnvironmentNameParam, packageNameParam, body, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Package, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (p *PackageServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if p.srv.Delete == nil {
		return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Automation/automationAccounts/(?P<automationAccountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/runtimeEnvironments/(?P<runtimeEnvironmentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/packages/(?P<packageName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	automationAccountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("automationAccountName")])
	if err != nil {
		return nil, err
	}
	runtimeEnvironmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("runtimeEnvironmentName")])
	if err != nil {
		return nil, err
	}
	packageNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("packageName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := p.srv.Delete(req.Context(), resourceGroupNameParam, automationAccountNameParam, runtimeEnvironmentNameParam, packageNameParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)}
	}
	resp, err := server.NewResponse(respContent, req, nil)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (p *PackageServerTransport) 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~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Automation/automationAccounts/(?P<automationAccountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/runtimeEnvironments/(?P<runtimeEnvironmentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/packages/(?P<packageName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	automationAccountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("automationAccountName")])
	if err != nil {
		return nil, err
	}
	runtimeEnvironmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("runtimeEnvironmentName")])
	if err != nil {
		return nil, err
	}
	packageNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("packageName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := p.srv.Get(req.Context(), resourceGroupNameParam, automationAccountNameParam, runtimeEnvironmentNameParam, packageNameParam, 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).Package, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (p *PackageServerTransport) dispatchNewListByRuntimeEnvironmentPager(req *http.Request) (*http.Response, error) {
	if p.srv.NewListByRuntimeEnvironmentPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByRuntimeEnvironmentPager not implemented")}
	}
	newListByRuntimeEnvironmentPager := p.newListByRuntimeEnvironmentPager.get(req)
	if newListByRuntimeEnvironmentPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Automation/automationAccounts/(?P<automationAccountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/runtimeEnvironments/(?P<runtimeEnvironmentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/packages`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 5 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		automationAccountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("automationAccountName")])
		if err != nil {
			return nil, err
		}
		runtimeEnvironmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("runtimeEnvironmentName")])
		if err != nil {
			return nil, err
		}
		resp := p.srv.NewListByRuntimeEnvironmentPager(resourceGroupNameParam, automationAccountNameParam, runtimeEnvironmentNameParam, nil)
		newListByRuntimeEnvironmentPager = &resp
		p.newListByRuntimeEnvironmentPager.add(req, newListByRuntimeEnvironmentPager)
		server.PagerResponderInjectNextLinks(newListByRuntimeEnvironmentPager, req, func(page *armautomation.PackageClientListByRuntimeEnvironmentResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByRuntimeEnvironmentPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		p.newListByRuntimeEnvironmentPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByRuntimeEnvironmentPager) {
		p.newListByRuntimeEnvironmentPager.remove(req)
	}
	return resp, nil
}

func (p *PackageServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) {
	if p.srv.Update == nil {
		return nil, &nonRetriableError{errors.New("fake for method Update not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Automation/automationAccounts/(?P<automationAccountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/runtimeEnvironments/(?P<runtimeEnvironmentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/packages/(?P<packageName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armautomation.PackageUpdateParameters](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	automationAccountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("automationAccountName")])
	if err != nil {
		return nil, err
	}
	runtimeEnvironmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("runtimeEnvironmentName")])
	if err != nil {
		return nil, err
	}
	packageNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("packageName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := p.srv.Update(req.Context(), resourceGroupNameParam, automationAccountNameParam, runtimeEnvironmentNameParam, packageNameParam, body, 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).Package, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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