// 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/deviceregistry/armdeviceregistry/v2"
	"net/http"
	"net/url"
	"regexp"
	"slices"
)

// SchemasServer is a fake server for instances of the armdeviceregistry.SchemasClient type.
type SchemasServer struct {
	// CreateOrReplace is the fake for method SchemasClient.CreateOrReplace
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrReplace func(ctx context.Context, resourceGroupName string, schemaRegistryName string, schemaName string, resource armdeviceregistry.Schema, options *armdeviceregistry.SchemasClientCreateOrReplaceOptions) (resp azfake.Responder[armdeviceregistry.SchemasClientCreateOrReplaceResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method SchemasClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, schemaRegistryName string, schemaName string, options *armdeviceregistry.SchemasClientBeginDeleteOptions) (resp azfake.PollerResponder[armdeviceregistry.SchemasClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method SchemasClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, schemaRegistryName string, schemaName string, options *armdeviceregistry.SchemasClientGetOptions) (resp azfake.Responder[armdeviceregistry.SchemasClientGetResponse], errResp azfake.ErrorResponder)

	// NewListBySchemaRegistryPager is the fake for method SchemasClient.NewListBySchemaRegistryPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListBySchemaRegistryPager func(resourceGroupName string, schemaRegistryName string, options *armdeviceregistry.SchemasClientListBySchemaRegistryOptions) (resp azfake.PagerResponder[armdeviceregistry.SchemasClientListBySchemaRegistryResponse])
}

// NewSchemasServerTransport creates a new instance of SchemasServerTransport with the provided implementation.
// The returned SchemasServerTransport instance is connected to an instance of armdeviceregistry.SchemasClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewSchemasServerTransport(srv *SchemasServer) *SchemasServerTransport {
	return &SchemasServerTransport{
		srv:                          srv,
		beginDelete:                  newTracker[azfake.PollerResponder[armdeviceregistry.SchemasClientDeleteResponse]](),
		newListBySchemaRegistryPager: newTracker[azfake.PagerResponder[armdeviceregistry.SchemasClientListBySchemaRegistryResponse]](),
	}
}

// SchemasServerTransport connects instances of armdeviceregistry.SchemasClient to instances of SchemasServer.
// Don't use this type directly, use NewSchemasServerTransport instead.
type SchemasServerTransport struct {
	srv                          *SchemasServer
	beginDelete                  *tracker[azfake.PollerResponder[armdeviceregistry.SchemasClientDeleteResponse]]
	newListBySchemaRegistryPager *tracker[azfake.PagerResponder[armdeviceregistry.SchemasClientListBySchemaRegistryResponse]]
}

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

func (s *SchemasServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if schemasServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = schemasServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "SchemasClient.CreateOrReplace":
				res.resp, res.err = s.dispatchCreateOrReplace(req)
			case "SchemasClient.BeginDelete":
				res.resp, res.err = s.dispatchBeginDelete(req)
			case "SchemasClient.Get":
				res.resp, res.err = s.dispatchGet(req)
			case "SchemasClient.NewListBySchemaRegistryPager":
				res.resp, res.err = s.dispatchNewListBySchemaRegistryPager(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 (s *SchemasServerTransport) dispatchCreateOrReplace(req *http.Request) (*http.Response, error) {
	if s.srv.CreateOrReplace == nil {
		return nil, &nonRetriableError{errors.New("fake for method CreateOrReplace not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DeviceRegistry/schemaRegistries/(?P<schemaRegistryName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/schemas/(?P<schemaName>[!#&$-;=?-\[\]_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[armdeviceregistry.Schema](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	schemaRegistryNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("schemaRegistryName")])
	if err != nil {
		return nil, err
	}
	schemaNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("schemaName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.CreateOrReplace(req.Context(), resourceGroupNameParam, schemaRegistryNameParam, schemaNameParam, 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).Schema, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (s *SchemasServerTransport) 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 = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DeviceRegistry/schemaRegistries/(?P<schemaRegistryName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/schemas/(?P<schemaName>[!#&$-;=?-\[\]_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
		}
		schemaRegistryNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("schemaRegistryName")])
		if err != nil {
			return nil, err
		}
		schemaNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("schemaName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := s.srv.BeginDelete(req.Context(), resourceGroupNameParam, schemaRegistryNameParam, schemaNameParam, nil)
		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 !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) {
		s.beginDelete.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)}
	}
	if !server.PollerResponderMore(beginDelete) {
		s.beginDelete.remove(req)
	}

	return resp, nil
}

func (s *SchemasServerTransport) 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 = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DeviceRegistry/schemaRegistries/(?P<schemaRegistryName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/schemas/(?P<schemaName>[!#&$-;=?-\[\]_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
	}
	schemaRegistryNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("schemaRegistryName")])
	if err != nil {
		return nil, err
	}
	schemaNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("schemaName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := s.srv.Get(req.Context(), resourceGroupNameParam, schemaRegistryNameParam, schemaNameParam, 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).Schema, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (s *SchemasServerTransport) dispatchNewListBySchemaRegistryPager(req *http.Request) (*http.Response, error) {
	if s.srv.NewListBySchemaRegistryPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListBySchemaRegistryPager not implemented")}
	}
	newListBySchemaRegistryPager := s.newListBySchemaRegistryPager.get(req)
	if newListBySchemaRegistryPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DeviceRegistry/schemaRegistries/(?P<schemaRegistryName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/schemas`
		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
		}
		schemaRegistryNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("schemaRegistryName")])
		if err != nil {
			return nil, err
		}
		resp := s.srv.NewListBySchemaRegistryPager(resourceGroupNameParam, schemaRegistryNameParam, nil)
		newListBySchemaRegistryPager = &resp
		s.newListBySchemaRegistryPager.add(req, newListBySchemaRegistryPager)
		server.PagerResponderInjectNextLinks(newListBySchemaRegistryPager, req, func(page *armdeviceregistry.SchemasClientListBySchemaRegistryResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListBySchemaRegistryPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		s.newListBySchemaRegistryPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListBySchemaRegistryPager) {
		s.newListBySchemaRegistryPager.remove(req)
	}
	return resp, nil
}

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