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

// FlexComponentsServer is a fake server for instances of the armoracledatabase.FlexComponentsClient type.
type FlexComponentsServer struct {
	// Get is the fake for method FlexComponentsClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, location string, flexComponentName string, options *armoracledatabase.FlexComponentsClientGetOptions) (resp azfake.Responder[armoracledatabase.FlexComponentsClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByParentPager is the fake for method FlexComponentsClient.NewListByParentPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByParentPager func(location string, options *armoracledatabase.FlexComponentsClientListByParentOptions) (resp azfake.PagerResponder[armoracledatabase.FlexComponentsClientListByParentResponse])
}

// NewFlexComponentsServerTransport creates a new instance of FlexComponentsServerTransport with the provided implementation.
// The returned FlexComponentsServerTransport instance is connected to an instance of armoracledatabase.FlexComponentsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewFlexComponentsServerTransport(srv *FlexComponentsServer) *FlexComponentsServerTransport {
	return &FlexComponentsServerTransport{
		srv:                  srv,
		newListByParentPager: newTracker[azfake.PagerResponder[armoracledatabase.FlexComponentsClientListByParentResponse]](),
	}
}

// FlexComponentsServerTransport connects instances of armoracledatabase.FlexComponentsClient to instances of FlexComponentsServer.
// Don't use this type directly, use NewFlexComponentsServerTransport instead.
type FlexComponentsServerTransport struct {
	srv                  *FlexComponentsServer
	newListByParentPager *tracker[azfake.PagerResponder[armoracledatabase.FlexComponentsClientListByParentResponse]]
}

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

func (f *FlexComponentsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if flexComponentsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = flexComponentsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "FlexComponentsClient.Get":
				res.resp, res.err = f.dispatchGet(req)
			case "FlexComponentsClient.NewListByParentPager":
				res.resp, res.err = f.dispatchNewListByParentPager(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 (f *FlexComponentsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if f.srv.Get == nil {
		return nil, &nonRetriableError{errors.New("fake for method Get not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P<location>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/flexComponents/(?P<flexComponentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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)
	}
	locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")])
	if err != nil {
		return nil, err
	}
	flexComponentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("flexComponentName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := f.srv.Get(req.Context(), locationParam, flexComponentNameParam, 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).FlexComponent, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (f *FlexComponentsServerTransport) dispatchNewListByParentPager(req *http.Request) (*http.Response, error) {
	if f.srv.NewListByParentPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByParentPager not implemented")}
	}
	newListByParentPager := f.newListByParentPager.get(req)
	if newListByParentPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P<location>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/flexComponents`
		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)
		}
		qp := req.URL.Query()
		locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")])
		if err != nil {
			return nil, err
		}
		shapeParam := getOptional(armoracledatabase.SystemShapes(qp.Get("shape")))
		var options *armoracledatabase.FlexComponentsClientListByParentOptions
		if shapeParam != nil {
			options = &armoracledatabase.FlexComponentsClientListByParentOptions{
				Shape: shapeParam,
			}
		}
		resp := f.srv.NewListByParentPager(locationParam, options)
		newListByParentPager = &resp
		f.newListByParentPager.add(req, newListByParentPager)
		server.PagerResponderInjectNextLinks(newListByParentPager, req, func(page *armoracledatabase.FlexComponentsClientListByParentResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByParentPager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		f.newListByParentPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByParentPager) {
		f.newListByParentPager.remove(req)
	}
	return resp, nil
}

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