// 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/postgresql/armpostgresqlflexibleservers/v6"
	"net/http"
	"net/url"
	"regexp"
	"slices"
)

// BackupsLongTermRetentionServer is a fake server for instances of the armpostgresqlflexibleservers.BackupsLongTermRetentionClient type.
type BackupsLongTermRetentionServer struct {
	// CheckPrerequisites is the fake for method BackupsLongTermRetentionClient.CheckPrerequisites
	// HTTP status codes to indicate success: http.StatusOK
	CheckPrerequisites func(ctx context.Context, resourceGroupName string, serverName string, parameters armpostgresqlflexibleservers.LtrPreBackupRequest, options *armpostgresqlflexibleservers.BackupsLongTermRetentionClientCheckPrerequisitesOptions) (resp azfake.Responder[armpostgresqlflexibleservers.BackupsLongTermRetentionClientCheckPrerequisitesResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method BackupsLongTermRetentionClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, serverName string, backupName string, options *armpostgresqlflexibleservers.BackupsLongTermRetentionClientGetOptions) (resp azfake.Responder[armpostgresqlflexibleservers.BackupsLongTermRetentionClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByServerPager is the fake for method BackupsLongTermRetentionClient.NewListByServerPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByServerPager func(resourceGroupName string, serverName string, options *armpostgresqlflexibleservers.BackupsLongTermRetentionClientListByServerOptions) (resp azfake.PagerResponder[armpostgresqlflexibleservers.BackupsLongTermRetentionClientListByServerResponse])

	// BeginStart is the fake for method BackupsLongTermRetentionClient.BeginStart
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginStart func(ctx context.Context, resourceGroupName string, serverName string, parameters armpostgresqlflexibleservers.BackupsLongTermRetentionRequest, options *armpostgresqlflexibleservers.BackupsLongTermRetentionClientBeginStartOptions) (resp azfake.PollerResponder[armpostgresqlflexibleservers.BackupsLongTermRetentionClientStartResponse], errResp azfake.ErrorResponder)
}

// NewBackupsLongTermRetentionServerTransport creates a new instance of BackupsLongTermRetentionServerTransport with the provided implementation.
// The returned BackupsLongTermRetentionServerTransport instance is connected to an instance of armpostgresqlflexibleservers.BackupsLongTermRetentionClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewBackupsLongTermRetentionServerTransport(srv *BackupsLongTermRetentionServer) *BackupsLongTermRetentionServerTransport {
	return &BackupsLongTermRetentionServerTransport{
		srv:                  srv,
		newListByServerPager: newTracker[azfake.PagerResponder[armpostgresqlflexibleservers.BackupsLongTermRetentionClientListByServerResponse]](),
		beginStart:           newTracker[azfake.PollerResponder[armpostgresqlflexibleservers.BackupsLongTermRetentionClientStartResponse]](),
	}
}

// BackupsLongTermRetentionServerTransport connects instances of armpostgresqlflexibleservers.BackupsLongTermRetentionClient to instances of BackupsLongTermRetentionServer.
// Don't use this type directly, use NewBackupsLongTermRetentionServerTransport instead.
type BackupsLongTermRetentionServerTransport struct {
	srv                  *BackupsLongTermRetentionServer
	newListByServerPager *tracker[azfake.PagerResponder[armpostgresqlflexibleservers.BackupsLongTermRetentionClientListByServerResponse]]
	beginStart           *tracker[azfake.PollerResponder[armpostgresqlflexibleservers.BackupsLongTermRetentionClientStartResponse]]
}

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

func (b *BackupsLongTermRetentionServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if backupsLongTermRetentionServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = backupsLongTermRetentionServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "BackupsLongTermRetentionClient.CheckPrerequisites":
				res.resp, res.err = b.dispatchCheckPrerequisites(req)
			case "BackupsLongTermRetentionClient.Get":
				res.resp, res.err = b.dispatchGet(req)
			case "BackupsLongTermRetentionClient.NewListByServerPager":
				res.resp, res.err = b.dispatchNewListByServerPager(req)
			case "BackupsLongTermRetentionClient.BeginStart":
				res.resp, res.err = b.dispatchBeginStart(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 (b *BackupsLongTermRetentionServerTransport) dispatchCheckPrerequisites(req *http.Request) (*http.Response, error) {
	if b.srv.CheckPrerequisites == nil {
		return nil, &nonRetriableError{errors.New("fake for method CheckPrerequisites not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DBforPostgreSQL/flexibleServers/(?P<serverName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/ltrPreBackup`
	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)
	}
	body, err := server.UnmarshalRequestAsJSON[armpostgresqlflexibleservers.LtrPreBackupRequest](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	serverNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serverName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := b.srv.CheckPrerequisites(req.Context(), resourceGroupNameParam, serverNameParam, 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).LtrPreBackupResponse, req)
	if err != nil {
		return nil, err
	}
	if val := server.GetResponse(respr).XMSRequestID; val != nil {
		resp.Header.Set("x-ms-request-id", *val)
	}
	return resp, nil
}

func (b *BackupsLongTermRetentionServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if b.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\.DBforPostgreSQL/flexibleServers/(?P<serverName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/ltrBackupOperations/(?P<backupName>[!#&$-;=?-\[\]_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
	}
	serverNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serverName")])
	if err != nil {
		return nil, err
	}
	backupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("backupName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := b.srv.Get(req.Context(), resourceGroupNameParam, serverNameParam, backupNameParam, 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).BackupsLongTermRetentionOperation, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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

func (b *BackupsLongTermRetentionServerTransport) dispatchBeginStart(req *http.Request) (*http.Response, error) {
	if b.srv.BeginStart == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginStart not implemented")}
	}
	beginStart := b.beginStart.get(req)
	if beginStart == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DBforPostgreSQL/flexibleServers/(?P<serverName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/startLtrBackup`
		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)
		}
		body, err := server.UnmarshalRequestAsJSON[armpostgresqlflexibleservers.BackupsLongTermRetentionRequest](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		serverNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serverName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := b.srv.BeginStart(req.Context(), resourceGroupNameParam, serverNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginStart = &respr
		b.beginStart.add(req, beginStart)
	}

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

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

	return resp, nil
}

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