// 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) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

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/v5"
	"net/http"
	"net/url"
	"regexp"
)

// MigrationsServer is a fake server for instances of the armpostgresqlflexibleservers.MigrationsClient type.
type MigrationsServer struct {
	// Create is the fake for method MigrationsClient.Create
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	Create func(ctx context.Context, subscriptionID string, resourceGroupName string, targetDbServerName string, migrationName string, parameters armpostgresqlflexibleservers.MigrationResource, options *armpostgresqlflexibleservers.MigrationsClientCreateOptions) (resp azfake.Responder[armpostgresqlflexibleservers.MigrationsClientCreateResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method MigrationsClient.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, subscriptionID string, resourceGroupName string, targetDbServerName string, migrationName string, options *armpostgresqlflexibleservers.MigrationsClientDeleteOptions) (resp azfake.Responder[armpostgresqlflexibleservers.MigrationsClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method MigrationsClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, subscriptionID string, resourceGroupName string, targetDbServerName string, migrationName string, options *armpostgresqlflexibleservers.MigrationsClientGetOptions) (resp azfake.Responder[armpostgresqlflexibleservers.MigrationsClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByTargetServerPager is the fake for method MigrationsClient.NewListByTargetServerPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByTargetServerPager func(subscriptionID string, resourceGroupName string, targetDbServerName string, options *armpostgresqlflexibleservers.MigrationsClientListByTargetServerOptions) (resp azfake.PagerResponder[armpostgresqlflexibleservers.MigrationsClientListByTargetServerResponse])

	// Update is the fake for method MigrationsClient.Update
	// HTTP status codes to indicate success: http.StatusOK
	Update func(ctx context.Context, subscriptionID string, resourceGroupName string, targetDbServerName string, migrationName string, parameters armpostgresqlflexibleservers.MigrationResourceForPatch, options *armpostgresqlflexibleservers.MigrationsClientUpdateOptions) (resp azfake.Responder[armpostgresqlflexibleservers.MigrationsClientUpdateResponse], errResp azfake.ErrorResponder)
}

// NewMigrationsServerTransport creates a new instance of MigrationsServerTransport with the provided implementation.
// The returned MigrationsServerTransport instance is connected to an instance of armpostgresqlflexibleservers.MigrationsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewMigrationsServerTransport(srv *MigrationsServer) *MigrationsServerTransport {
	return &MigrationsServerTransport{
		srv:                        srv,
		newListByTargetServerPager: newTracker[azfake.PagerResponder[armpostgresqlflexibleservers.MigrationsClientListByTargetServerResponse]](),
	}
}

// MigrationsServerTransport connects instances of armpostgresqlflexibleservers.MigrationsClient to instances of MigrationsServer.
// Don't use this type directly, use NewMigrationsServerTransport instead.
type MigrationsServerTransport struct {
	srv                        *MigrationsServer
	newListByTargetServerPager *tracker[azfake.PagerResponder[armpostgresqlflexibleservers.MigrationsClientListByTargetServerResponse]]
}

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

func (m *MigrationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result)
	defer close(resultChan)

	go func() {
		var intercepted bool
		var res result
		if migrationsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = migrationsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "MigrationsClient.Create":
				res.resp, res.err = m.dispatchCreate(req)
			case "MigrationsClient.Delete":
				res.resp, res.err = m.dispatchDelete(req)
			case "MigrationsClient.Get":
				res.resp, res.err = m.dispatchGet(req)
			case "MigrationsClient.NewListByTargetServerPager":
				res.resp, res.err = m.dispatchNewListByTargetServerPager(req)
			case "MigrationsClient.Update":
				res.resp, res.err = m.dispatchUpdate(req)
			default:
				res.err = fmt.Errorf("unhandled API %s", method)
			}

		}
		select {
		case resultChan <- res:
		case <-req.Context().Done():
		}
	}()

	select {
	case <-req.Context().Done():
		return nil, req.Context().Err()
	case res := <-resultChan:
		return res.resp, res.err
	}
}

func (m *MigrationsServerTransport) dispatchCreate(req *http.Request) (*http.Response, error) {
	if m.srv.Create == nil {
		return nil, &nonRetriableError{errors.New("fake for method Create not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DBforPostgreSQL/flexibleServers/(?P<targetDbServerName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/migrations/(?P<migrationName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 4 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armpostgresqlflexibleservers.MigrationResource](req)
	if err != nil {
		return nil, err
	}
	subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")])
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	targetDbServerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("targetDbServerName")])
	if err != nil {
		return nil, err
	}
	migrationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("migrationName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := m.srv.Create(req.Context(), subscriptionIDParam, resourceGroupNameParam, targetDbServerNameParam, migrationNameParam, body, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !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).MigrationResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (m *MigrationsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if m.srv.Delete == nil {
		return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DBforPostgreSQL/flexibleServers/(?P<targetDbServerName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/migrations/(?P<migrationName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 4 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")])
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	targetDbServerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("targetDbServerName")])
	if err != nil {
		return nil, err
	}
	migrationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("migrationName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := m.srv.Delete(req.Context(), subscriptionIDParam, resourceGroupNameParam, targetDbServerNameParam, migrationNameParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)}
	}
	resp, err := server.NewResponse(respContent, req, nil)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (m *MigrationsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if m.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<targetDbServerName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/migrations/(?P<migrationName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 4 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")])
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	targetDbServerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("targetDbServerName")])
	if err != nil {
		return nil, err
	}
	migrationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("migrationName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := m.srv.Get(req.Context(), subscriptionIDParam, resourceGroupNameParam, targetDbServerNameParam, migrationNameParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !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).MigrationResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (m *MigrationsServerTransport) dispatchNewListByTargetServerPager(req *http.Request) (*http.Response, error) {
	if m.srv.NewListByTargetServerPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByTargetServerPager not implemented")}
	}
	newListByTargetServerPager := m.newListByTargetServerPager.get(req)
	if newListByTargetServerPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DBforPostgreSQL/flexibleServers/(?P<targetDbServerName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/migrations`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 3 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		qp := req.URL.Query()
		subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")])
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		targetDbServerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("targetDbServerName")])
		if err != nil {
			return nil, err
		}
		migrationListFilterUnescaped, err := url.QueryUnescape(qp.Get("migrationListFilter"))
		if err != nil {
			return nil, err
		}
		migrationListFilterParam := getOptional(armpostgresqlflexibleservers.MigrationListFilter(migrationListFilterUnescaped))
		var options *armpostgresqlflexibleservers.MigrationsClientListByTargetServerOptions
		if migrationListFilterParam != nil {
			options = &armpostgresqlflexibleservers.MigrationsClientListByTargetServerOptions{
				MigrationListFilter: migrationListFilterParam,
			}
		}
		resp := m.srv.NewListByTargetServerPager(subscriptionIDParam, resourceGroupNameParam, targetDbServerNameParam, options)
		newListByTargetServerPager = &resp
		m.newListByTargetServerPager.add(req, newListByTargetServerPager)
		server.PagerResponderInjectNextLinks(newListByTargetServerPager, req, func(page *armpostgresqlflexibleservers.MigrationsClientListByTargetServerResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByTargetServerPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		m.newListByTargetServerPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByTargetServerPager) {
		m.newListByTargetServerPager.remove(req)
	}
	return resp, nil
}

func (m *MigrationsServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) {
	if m.srv.Update == nil {
		return nil, &nonRetriableError{errors.New("fake for method Update not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DBforPostgreSQL/flexibleServers/(?P<targetDbServerName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/migrations/(?P<migrationName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 4 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armpostgresqlflexibleservers.MigrationResourceForPatch](req)
	if err != nil {
		return nil, err
	}
	subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")])
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	targetDbServerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("targetDbServerName")])
	if err != nil {
		return nil, err
	}
	migrationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("migrationName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := m.srv.Update(req.Context(), subscriptionIDParam, resourceGroupNameParam, targetDbServerNameParam, migrationNameParam, body, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !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).MigrationResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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