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

// JobStreamServer is a fake server for instances of the armautomation.JobStreamClient type.
type JobStreamServer struct {
	// Get is the fake for method JobStreamClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, automationAccountName string, jobName string, jobStreamID string, options *armautomation.JobStreamClientGetOptions) (resp azfake.Responder[armautomation.JobStreamClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByJobPager is the fake for method JobStreamClient.NewListByJobPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByJobPager func(resourceGroupName string, automationAccountName string, jobName string, options *armautomation.JobStreamClientListByJobOptions) (resp azfake.PagerResponder[armautomation.JobStreamClientListByJobResponse])
}

// NewJobStreamServerTransport creates a new instance of JobStreamServerTransport with the provided implementation.
// The returned JobStreamServerTransport instance is connected to an instance of armautomation.JobStreamClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewJobStreamServerTransport(srv *JobStreamServer) *JobStreamServerTransport {
	return &JobStreamServerTransport{
		srv:               srv,
		newListByJobPager: newTracker[azfake.PagerResponder[armautomation.JobStreamClientListByJobResponse]](),
	}
}

// JobStreamServerTransport connects instances of armautomation.JobStreamClient to instances of JobStreamServer.
// Don't use this type directly, use NewJobStreamServerTransport instead.
type JobStreamServerTransport struct {
	srv               *JobStreamServer
	newListByJobPager *tracker[azfake.PagerResponder[armautomation.JobStreamClientListByJobResponse]]
}

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

func (j *JobStreamServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if jobStreamServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = jobStreamServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "JobStreamClient.Get":
				res.resp, res.err = j.dispatchGet(req)
			case "JobStreamClient.NewListByJobPager":
				res.resp, res.err = j.dispatchNewListByJobPager(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 (j *JobStreamServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if j.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~%@]+)/jobs/(?P<jobName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/streams/(?P<jobStreamId>[!#&$-;=?-\[\]_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
	}
	jobNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("jobName")])
	if err != nil {
		return nil, err
	}
	jobStreamIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("jobStreamId")])
	if err != nil {
		return nil, err
	}
	clientRequestIDParam := getOptional(getHeaderValue(req.Header, "clientRequestId"))
	var options *armautomation.JobStreamClientGetOptions
	if clientRequestIDParam != nil {
		options = &armautomation.JobStreamClientGetOptions{
			ClientRequestID: clientRequestIDParam,
		}
	}
	respr, errRespr := j.srv.Get(req.Context(), resourceGroupNameParam, automationAccountNameParam, jobNameParam, jobStreamIDParam, options)
	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).JobStream, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (j *JobStreamServerTransport) dispatchNewListByJobPager(req *http.Request) (*http.Response, error) {
	if j.srv.NewListByJobPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByJobPager not implemented")}
	}
	newListByJobPager := j.newListByJobPager.get(req)
	if newListByJobPager == 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~%@]+)/jobs/(?P<jobName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/streams`
		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)
		}
		qp := req.URL.Query()
		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
		}
		jobNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("jobName")])
		if err != nil {
			return nil, err
		}
		filterParam := getOptional(qp.Get("$filter"))
		clientRequestIDParam := getOptional(getHeaderValue(req.Header, "clientRequestId"))
		var options *armautomation.JobStreamClientListByJobOptions
		if filterParam != nil || clientRequestIDParam != nil {
			options = &armautomation.JobStreamClientListByJobOptions{
				Filter:          filterParam,
				ClientRequestID: clientRequestIDParam,
			}
		}
		resp := j.srv.NewListByJobPager(resourceGroupNameParam, automationAccountNameParam, jobNameParam, options)
		newListByJobPager = &resp
		j.newListByJobPager.add(req, newListByJobPager)
		server.PagerResponderInjectNextLinks(newListByJobPager, req, func(page *armautomation.JobStreamClientListByJobResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByJobPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		j.newListByJobPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByJobPager) {
		j.newListByJobPager.remove(req)
	}
	return resp, nil
}

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