// 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/support/armsupport/v2"
	"net/http"
	"net/url"
	"regexp"
	"slices"
	"strconv"
)

// CommunicationsNoSubscriptionServer is a fake server for instances of the armsupport.CommunicationsNoSubscriptionClient type.
type CommunicationsNoSubscriptionServer struct {
	// CheckNameAvailability is the fake for method CommunicationsNoSubscriptionClient.CheckNameAvailability
	// HTTP status codes to indicate success: http.StatusOK
	CheckNameAvailability func(ctx context.Context, supportTicketName string, checkNameAvailabilityInput armsupport.CheckNameAvailabilityInput, options *armsupport.CommunicationsNoSubscriptionClientCheckNameAvailabilityOptions) (resp azfake.Responder[armsupport.CommunicationsNoSubscriptionClientCheckNameAvailabilityResponse], errResp azfake.ErrorResponder)

	// BeginCreate is the fake for method CommunicationsNoSubscriptionClient.BeginCreate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginCreate func(ctx context.Context, supportTicketName string, communicationName string, createCommunicationParameters armsupport.CommunicationDetails, options *armsupport.CommunicationsNoSubscriptionClientBeginCreateOptions) (resp azfake.PollerResponder[armsupport.CommunicationsNoSubscriptionClientCreateResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method CommunicationsNoSubscriptionClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, supportTicketName string, communicationName string, options *armsupport.CommunicationsNoSubscriptionClientGetOptions) (resp azfake.Responder[armsupport.CommunicationsNoSubscriptionClientGetResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method CommunicationsNoSubscriptionClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(supportTicketName string, options *armsupport.CommunicationsNoSubscriptionClientListOptions) (resp azfake.PagerResponder[armsupport.CommunicationsNoSubscriptionClientListResponse])
}

// NewCommunicationsNoSubscriptionServerTransport creates a new instance of CommunicationsNoSubscriptionServerTransport with the provided implementation.
// The returned CommunicationsNoSubscriptionServerTransport instance is connected to an instance of armsupport.CommunicationsNoSubscriptionClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewCommunicationsNoSubscriptionServerTransport(srv *CommunicationsNoSubscriptionServer) *CommunicationsNoSubscriptionServerTransport {
	return &CommunicationsNoSubscriptionServerTransport{
		srv:          srv,
		beginCreate:  newTracker[azfake.PollerResponder[armsupport.CommunicationsNoSubscriptionClientCreateResponse]](),
		newListPager: newTracker[azfake.PagerResponder[armsupport.CommunicationsNoSubscriptionClientListResponse]](),
	}
}

// CommunicationsNoSubscriptionServerTransport connects instances of armsupport.CommunicationsNoSubscriptionClient to instances of CommunicationsNoSubscriptionServer.
// Don't use this type directly, use NewCommunicationsNoSubscriptionServerTransport instead.
type CommunicationsNoSubscriptionServerTransport struct {
	srv          *CommunicationsNoSubscriptionServer
	beginCreate  *tracker[azfake.PollerResponder[armsupport.CommunicationsNoSubscriptionClientCreateResponse]]
	newListPager *tracker[azfake.PagerResponder[armsupport.CommunicationsNoSubscriptionClientListResponse]]
}

// Do implements the policy.Transporter interface for CommunicationsNoSubscriptionServerTransport.
func (c *CommunicationsNoSubscriptionServerTransport) 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 *CommunicationsNoSubscriptionServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if communicationsNoSubscriptionServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = communicationsNoSubscriptionServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "CommunicationsNoSubscriptionClient.CheckNameAvailability":
				res.resp, res.err = c.dispatchCheckNameAvailability(req)
			case "CommunicationsNoSubscriptionClient.BeginCreate":
				res.resp, res.err = c.dispatchBeginCreate(req)
			case "CommunicationsNoSubscriptionClient.Get":
				res.resp, res.err = c.dispatchGet(req)
			case "CommunicationsNoSubscriptionClient.NewListPager":
				res.resp, res.err = c.dispatchNewListPager(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 *CommunicationsNoSubscriptionServerTransport) dispatchCheckNameAvailability(req *http.Request) (*http.Response, error) {
	if c.srv.CheckNameAvailability == nil {
		return nil, &nonRetriableError{errors.New("fake for method CheckNameAvailability not implemented")}
	}
	const regexStr = `/providers/Microsoft\.Support/supportTickets/(?P<supportTicketName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/checkNameAvailability`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 2 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armsupport.CheckNameAvailabilityInput](req)
	if err != nil {
		return nil, err
	}
	supportTicketNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("supportTicketName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := c.srv.CheckNameAvailability(req.Context(), supportTicketNameParam, 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).CheckNameAvailabilityOutput, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *CommunicationsNoSubscriptionServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) {
	if c.srv.BeginCreate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")}
	}
	beginCreate := c.beginCreate.get(req)
	if beginCreate == nil {
		const regexStr = `/providers/Microsoft\.Support/supportTickets/(?P<supportTicketName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/communications/(?P<communicationName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 3 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		body, err := server.UnmarshalRequestAsJSON[armsupport.CommunicationDetails](req)
		if err != nil {
			return nil, err
		}
		supportTicketNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("supportTicketName")])
		if err != nil {
			return nil, err
		}
		communicationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("communicationName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := c.srv.BeginCreate(req.Context(), supportTicketNameParam, communicationNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreate = &respr
		c.beginCreate.add(req, beginCreate)
	}

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

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

	return resp, nil
}

func (c *CommunicationsNoSubscriptionServerTransport) 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 = `/providers/Microsoft\.Support/supportTickets/(?P<supportTicketName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/communications/(?P<communicationName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 3 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	supportTicketNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("supportTicketName")])
	if err != nil {
		return nil, err
	}
	communicationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("communicationName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := c.srv.Get(req.Context(), supportTicketNameParam, communicationNameParam, 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).CommunicationDetails, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *CommunicationsNoSubscriptionServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if c.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := c.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/providers/Microsoft\.Support/supportTickets/(?P<supportTicketName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/communications`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 2 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		qp := req.URL.Query()
		supportTicketNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("supportTicketName")])
		if err != nil {
			return nil, err
		}
		topParam, err := parseOptional(qp.Get("$top"), 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
		}
		filterParam := getOptional(qp.Get("$filter"))
		var options *armsupport.CommunicationsNoSubscriptionClientListOptions
		if topParam != nil || filterParam != nil {
			options = &armsupport.CommunicationsNoSubscriptionClientListOptions{
				Top:    topParam,
				Filter: filterParam,
			}
		}
		resp := c.srv.NewListPager(supportTicketNameParam, options)
		newListPager = &resp
		c.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armsupport.CommunicationsNoSubscriptionClientListResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		c.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		c.newListPager.remove(req)
	}
	return resp, nil
}

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