// 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/security/keyvault/azadmin/backup"
	"net/http"
	"net/url"
	"regexp"
	"slices"
)

// Server is a fake server for instances of the backup.Client type.
type Server struct {
	// BeginFullBackup is the fake for method Client.BeginFullBackup
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginFullBackup func(ctx context.Context, azureStorageBlobContainerURI backup.SASTokenParameters, options *backup.BeginFullBackupOptions) (resp azfake.PollerResponder[backup.FullBackupResponse], errResp azfake.ErrorResponder)

	// BeginFullRestore is the fake for method Client.BeginFullRestore
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginFullRestore func(ctx context.Context, restoreBlobDetails backup.RestoreOperationParameters, options *backup.BeginFullRestoreOptions) (resp azfake.PollerResponder[backup.FullRestoreResponse], errResp azfake.ErrorResponder)

	// BeginPreFullBackup is the fake for method Client.BeginPreFullBackup
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginPreFullBackup func(ctx context.Context, preBackupOperationParameters backup.PreBackupOperationParameters, options *backup.BeginPreFullBackupOptions) (resp azfake.PollerResponder[backup.PreFullBackupResponse], errResp azfake.ErrorResponder)

	// BeginPreFullRestore is the fake for method Client.BeginPreFullRestore
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginPreFullRestore func(ctx context.Context, preRestoreOperationParameters backup.PreRestoreOperationParameters, options *backup.BeginPreFullRestoreOptions) (resp azfake.PollerResponder[backup.PreFullRestoreResponse], errResp azfake.ErrorResponder)

	// BeginSelectiveKeyRestore is the fake for method Client.BeginSelectiveKeyRestore
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginSelectiveKeyRestore func(ctx context.Context, keyName string, restoreBlobDetails backup.SelectiveKeyRestoreOperationParameters, options *backup.BeginSelectiveKeyRestoreOptions) (resp azfake.PollerResponder[backup.SelectiveKeyRestoreResponse], errResp azfake.ErrorResponder)
}

// NewServerTransport creates a new instance of ServerTransport with the provided implementation.
// The returned ServerTransport instance is connected to an instance of backup.Client via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewServerTransport(srv *Server) *ServerTransport {
	return &ServerTransport{
		srv:                      srv,
		beginFullBackup:          newTracker[azfake.PollerResponder[backup.FullBackupResponse]](),
		beginFullRestore:         newTracker[azfake.PollerResponder[backup.FullRestoreResponse]](),
		beginPreFullBackup:       newTracker[azfake.PollerResponder[backup.PreFullBackupResponse]](),
		beginPreFullRestore:      newTracker[azfake.PollerResponder[backup.PreFullRestoreResponse]](),
		beginSelectiveKeyRestore: newTracker[azfake.PollerResponder[backup.SelectiveKeyRestoreResponse]](),
	}
}

// ServerTransport connects instances of backup.Client to instances of Server.
// Don't use this type directly, use NewServerTransport instead.
type ServerTransport struct {
	srv                      *Server
	beginFullBackup          *tracker[azfake.PollerResponder[backup.FullBackupResponse]]
	beginFullRestore         *tracker[azfake.PollerResponder[backup.FullRestoreResponse]]
	beginPreFullBackup       *tracker[azfake.PollerResponder[backup.PreFullBackupResponse]]
	beginPreFullRestore      *tracker[azfake.PollerResponder[backup.PreFullRestoreResponse]]
	beginSelectiveKeyRestore *tracker[azfake.PollerResponder[backup.SelectiveKeyRestoreResponse]]
}

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

func (s *ServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if serverTransportInterceptor != nil {
			res.resp, res.err, intercepted = serverTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "Client.BeginFullBackup":
				res.resp, res.err = s.dispatchBeginFullBackup(req)
			case "Client.BeginFullRestore":
				res.resp, res.err = s.dispatchBeginFullRestore(req)
			case "Client.BeginPreFullBackup":
				res.resp, res.err = s.dispatchBeginPreFullBackup(req)
			case "Client.BeginPreFullRestore":
				res.resp, res.err = s.dispatchBeginPreFullRestore(req)
			case "Client.BeginSelectiveKeyRestore":
				res.resp, res.err = s.dispatchBeginSelectiveKeyRestore(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 (s *ServerTransport) dispatchBeginFullBackup(req *http.Request) (*http.Response, error) {
	if s.srv.BeginFullBackup == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginFullBackup not implemented")}
	}
	beginFullBackup := s.beginFullBackup.get(req)
	if beginFullBackup == nil {
		body, err := server.UnmarshalRequestAsJSON[backup.SASTokenParameters](req)
		if err != nil {
			return nil, err
		}
		respr, errRespr := s.srv.BeginFullBackup(req.Context(), body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginFullBackup = &respr
		s.beginFullBackup.add(req, beginFullBackup)
	}

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

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

	return resp, nil
}

func (s *ServerTransport) dispatchBeginFullRestore(req *http.Request) (*http.Response, error) {
	if s.srv.BeginFullRestore == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginFullRestore not implemented")}
	}
	beginFullRestore := s.beginFullRestore.get(req)
	if beginFullRestore == nil {
		body, err := server.UnmarshalRequestAsJSON[backup.RestoreOperationParameters](req)
		if err != nil {
			return nil, err
		}
		respr, errRespr := s.srv.BeginFullRestore(req.Context(), body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginFullRestore = &respr
		s.beginFullRestore.add(req, beginFullRestore)
	}

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

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

	return resp, nil
}

func (s *ServerTransport) dispatchBeginPreFullBackup(req *http.Request) (*http.Response, error) {
	if s.srv.BeginPreFullBackup == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginPreFullBackup not implemented")}
	}
	beginPreFullBackup := s.beginPreFullBackup.get(req)
	if beginPreFullBackup == nil {
		body, err := server.UnmarshalRequestAsJSON[backup.PreBackupOperationParameters](req)
		if err != nil {
			return nil, err
		}
		respr, errRespr := s.srv.BeginPreFullBackup(req.Context(), body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginPreFullBackup = &respr
		s.beginPreFullBackup.add(req, beginPreFullBackup)
	}

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

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

	return resp, nil
}

func (s *ServerTransport) dispatchBeginPreFullRestore(req *http.Request) (*http.Response, error) {
	if s.srv.BeginPreFullRestore == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginPreFullRestore not implemented")}
	}
	beginPreFullRestore := s.beginPreFullRestore.get(req)
	if beginPreFullRestore == nil {
		body, err := server.UnmarshalRequestAsJSON[backup.PreRestoreOperationParameters](req)
		if err != nil {
			return nil, err
		}
		respr, errRespr := s.srv.BeginPreFullRestore(req.Context(), body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginPreFullRestore = &respr
		s.beginPreFullRestore.add(req, beginPreFullRestore)
	}

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

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

	return resp, nil
}

func (s *ServerTransport) dispatchBeginSelectiveKeyRestore(req *http.Request) (*http.Response, error) {
	if s.srv.BeginSelectiveKeyRestore == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginSelectiveKeyRestore not implemented")}
	}
	beginSelectiveKeyRestore := s.beginSelectiveKeyRestore.get(req)
	if beginSelectiveKeyRestore == nil {
		const regexStr = `/keys/(?P<keyName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/restore`
		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[backup.SelectiveKeyRestoreOperationParameters](req)
		if err != nil {
			return nil, err
		}
		keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("keyName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := s.srv.BeginSelectiveKeyRestore(req.Context(), keyNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginSelectiveKeyRestore = &respr
		s.beginSelectiveKeyRestore.add(req, beginSelectiveKeyRestore)
	}

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

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

	return resp, nil
}

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