// 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"
)

// ConnectionTypeServer is a fake server for instances of the armautomation.ConnectionTypeClient type.
type ConnectionTypeServer struct {
	// CreateOrUpdate is the fake for method ConnectionTypeClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusCreated
	CreateOrUpdate func(ctx context.Context, resourceGroupName string, automationAccountName string, connectionTypeName string, parameters armautomation.ConnectionTypeCreateOrUpdateParameters, options *armautomation.ConnectionTypeClientCreateOrUpdateOptions) (resp azfake.Responder[armautomation.ConnectionTypeClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

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

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

	// NewListByAutomationAccountPager is the fake for method ConnectionTypeClient.NewListByAutomationAccountPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByAutomationAccountPager func(resourceGroupName string, automationAccountName string, options *armautomation.ConnectionTypeClientListByAutomationAccountOptions) (resp azfake.PagerResponder[armautomation.ConnectionTypeClientListByAutomationAccountResponse])
}

// NewConnectionTypeServerTransport creates a new instance of ConnectionTypeServerTransport with the provided implementation.
// The returned ConnectionTypeServerTransport instance is connected to an instance of armautomation.ConnectionTypeClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewConnectionTypeServerTransport(srv *ConnectionTypeServer) *ConnectionTypeServerTransport {
	return &ConnectionTypeServerTransport{
		srv:                             srv,
		newListByAutomationAccountPager: newTracker[azfake.PagerResponder[armautomation.ConnectionTypeClientListByAutomationAccountResponse]](),
	}
}

// ConnectionTypeServerTransport connects instances of armautomation.ConnectionTypeClient to instances of ConnectionTypeServer.
// Don't use this type directly, use NewConnectionTypeServerTransport instead.
type ConnectionTypeServerTransport struct {
	srv                             *ConnectionTypeServer
	newListByAutomationAccountPager *tracker[azfake.PagerResponder[armautomation.ConnectionTypeClientListByAutomationAccountResponse]]
}

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

func (c *ConnectionTypeServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if connectionTypeServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = connectionTypeServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "ConnectionTypeClient.CreateOrUpdate":
				res.resp, res.err = c.dispatchCreateOrUpdate(req)
			case "ConnectionTypeClient.Delete":
				res.resp, res.err = c.dispatchDelete(req)
			case "ConnectionTypeClient.Get":
				res.resp, res.err = c.dispatchGet(req)
			case "ConnectionTypeClient.NewListByAutomationAccountPager":
				res.resp, res.err = c.dispatchNewListByAutomationAccountPager(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 (c *ConnectionTypeServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if c.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~%@]+)/connectionTypes/(?P<connectionTypeName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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)
	}
	body, err := server.UnmarshalRequestAsJSON[armautomation.ConnectionTypeCreateOrUpdateParameters](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
	}
	connectionTypeNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectionTypeName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := c.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, automationAccountNameParam, connectionTypeNameParam, body, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !slices.Contains([]int{http.StatusCreated}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusCreated", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ConnectionType, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *ConnectionTypeServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if c.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~%@]+)/connectionTypes/(?P<connectionTypeName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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
	}
	connectionTypeNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectionTypeName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := c.srv.Delete(req.Context(), resourceGroupNameParam, automationAccountNameParam, connectionTypeNameParam, 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 (c *ConnectionTypeServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if c.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~%@]+)/connectionTypes/(?P<connectionTypeName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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
	}
	connectionTypeNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectionTypeName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := c.srv.Get(req.Context(), resourceGroupNameParam, automationAccountNameParam, connectionTypeNameParam, 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).ConnectionType, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *ConnectionTypeServerTransport) dispatchNewListByAutomationAccountPager(req *http.Request) (*http.Response, error) {
	if c.srv.NewListByAutomationAccountPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByAutomationAccountPager not implemented")}
	}
	newListByAutomationAccountPager := c.newListByAutomationAccountPager.get(req)
	if newListByAutomationAccountPager == 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~%@]+)/connectionTypes`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 4 {
			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
		}
		resp := c.srv.NewListByAutomationAccountPager(resourceGroupNameParam, automationAccountNameParam, nil)
		newListByAutomationAccountPager = &resp
		c.newListByAutomationAccountPager.add(req, newListByAutomationAccountPager)
		server.PagerResponderInjectNextLinks(newListByAutomationAccountPager, req, func(page *armautomation.ConnectionTypeClientListByAutomationAccountResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByAutomationAccountPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		c.newListByAutomationAccountPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByAutomationAccountPager) {
		c.newListByAutomationAccountPager.remove(req)
	}
	return resp, nil
}

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