// 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/sql/armsql/v2"
	"net/http"
	"net/url"
	"regexp"
)

// ManagedDatabaseColumnsServer is a fake server for instances of the armsql.ManagedDatabaseColumnsClient type.
type ManagedDatabaseColumnsServer struct {
	// Get is the fake for method ManagedDatabaseColumnsClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, schemaName string, tableName string, columnName string, options *armsql.ManagedDatabaseColumnsClientGetOptions) (resp azfake.Responder[armsql.ManagedDatabaseColumnsClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByDatabasePager is the fake for method ManagedDatabaseColumnsClient.NewListByDatabasePager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByDatabasePager func(resourceGroupName string, managedInstanceName string, databaseName string, options *armsql.ManagedDatabaseColumnsClientListByDatabaseOptions) (resp azfake.PagerResponder[armsql.ManagedDatabaseColumnsClientListByDatabaseResponse])

	// NewListByTablePager is the fake for method ManagedDatabaseColumnsClient.NewListByTablePager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByTablePager func(resourceGroupName string, managedInstanceName string, databaseName string, schemaName string, tableName string, options *armsql.ManagedDatabaseColumnsClientListByTableOptions) (resp azfake.PagerResponder[armsql.ManagedDatabaseColumnsClientListByTableResponse])
}

// NewManagedDatabaseColumnsServerTransport creates a new instance of ManagedDatabaseColumnsServerTransport with the provided implementation.
// The returned ManagedDatabaseColumnsServerTransport instance is connected to an instance of armsql.ManagedDatabaseColumnsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewManagedDatabaseColumnsServerTransport(srv *ManagedDatabaseColumnsServer) *ManagedDatabaseColumnsServerTransport {
	return &ManagedDatabaseColumnsServerTransport{
		srv:                    srv,
		newListByDatabasePager: newTracker[azfake.PagerResponder[armsql.ManagedDatabaseColumnsClientListByDatabaseResponse]](),
		newListByTablePager:    newTracker[azfake.PagerResponder[armsql.ManagedDatabaseColumnsClientListByTableResponse]](),
	}
}

// ManagedDatabaseColumnsServerTransport connects instances of armsql.ManagedDatabaseColumnsClient to instances of ManagedDatabaseColumnsServer.
// Don't use this type directly, use NewManagedDatabaseColumnsServerTransport instead.
type ManagedDatabaseColumnsServerTransport struct {
	srv                    *ManagedDatabaseColumnsServer
	newListByDatabasePager *tracker[azfake.PagerResponder[armsql.ManagedDatabaseColumnsClientListByDatabaseResponse]]
	newListByTablePager    *tracker[azfake.PagerResponder[armsql.ManagedDatabaseColumnsClientListByTableResponse]]
}

// Do implements the policy.Transporter interface for ManagedDatabaseColumnsServerTransport.
func (m *ManagedDatabaseColumnsServerTransport) 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 *ManagedDatabaseColumnsServerTransport) 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 managedDatabaseColumnsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = managedDatabaseColumnsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "ManagedDatabaseColumnsClient.Get":
				res.resp, res.err = m.dispatchGet(req)
			case "ManagedDatabaseColumnsClient.NewListByDatabasePager":
				res.resp, res.err = m.dispatchNewListByDatabasePager(req)
			case "ManagedDatabaseColumnsClient.NewListByTablePager":
				res.resp, res.err = m.dispatchNewListByTablePager(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 *ManagedDatabaseColumnsServerTransport) 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\.Sql/managedInstances/(?P<managedInstanceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P<databaseName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/schemas/(?P<schemaName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tables/(?P<tableName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/columns/(?P<columnName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 8 {
		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
	}
	managedInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedInstanceName")])
	if err != nil {
		return nil, err
	}
	databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")])
	if err != nil {
		return nil, err
	}
	schemaNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("schemaName")])
	if err != nil {
		return nil, err
	}
	tableNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("tableName")])
	if err != nil {
		return nil, err
	}
	columnNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("columnName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := m.srv.Get(req.Context(), resourceGroupNameParam, managedInstanceNameParam, databaseNameParam, schemaNameParam, tableNameParam, columnNameParam, 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).DatabaseColumn, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (m *ManagedDatabaseColumnsServerTransport) dispatchNewListByDatabasePager(req *http.Request) (*http.Response, error) {
	if m.srv.NewListByDatabasePager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByDatabasePager not implemented")}
	}
	newListByDatabasePager := m.newListByDatabasePager.get(req)
	if newListByDatabasePager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Sql/managedInstances/(?P<managedInstanceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P<databaseName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/columns`
		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
		}
		managedInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedInstanceName")])
		if err != nil {
			return nil, err
		}
		databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")])
		if err != nil {
			return nil, err
		}
		schemaEscaped := qp["schema"]
		schemaParam := make([]string, len(schemaEscaped))
		for i, v := range schemaEscaped {
			u, unescapeErr := url.QueryUnescape(v)
			if unescapeErr != nil {
				return nil, unescapeErr
			}
			schemaParam[i] = u
		}
		tableEscaped := qp["table"]
		tableParam := make([]string, len(tableEscaped))
		for i, v := range tableEscaped {
			u, unescapeErr := url.QueryUnescape(v)
			if unescapeErr != nil {
				return nil, unescapeErr
			}
			tableParam[i] = u
		}
		columnEscaped := qp["column"]
		columnParam := make([]string, len(columnEscaped))
		for i, v := range columnEscaped {
			u, unescapeErr := url.QueryUnescape(v)
			if unescapeErr != nil {
				return nil, unescapeErr
			}
			columnParam[i] = u
		}
		orderByEscaped := qp["orderBy"]
		orderByParam := make([]string, len(orderByEscaped))
		for i, v := range orderByEscaped {
			u, unescapeErr := url.QueryUnescape(v)
			if unescapeErr != nil {
				return nil, unescapeErr
			}
			orderByParam[i] = u
		}
		skiptokenUnescaped, err := url.QueryUnescape(qp.Get("$skiptoken"))
		if err != nil {
			return nil, err
		}
		skiptokenParam := getOptional(skiptokenUnescaped)
		var options *armsql.ManagedDatabaseColumnsClientListByDatabaseOptions
		if len(schemaParam) > 0 || len(tableParam) > 0 || len(columnParam) > 0 || len(orderByParam) > 0 || skiptokenParam != nil {
			options = &armsql.ManagedDatabaseColumnsClientListByDatabaseOptions{
				Schema:    schemaParam,
				Table:     tableParam,
				Column:    columnParam,
				OrderBy:   orderByParam,
				Skiptoken: skiptokenParam,
			}
		}
		resp := m.srv.NewListByDatabasePager(resourceGroupNameParam, managedInstanceNameParam, databaseNameParam, options)
		newListByDatabasePager = &resp
		m.newListByDatabasePager.add(req, newListByDatabasePager)
		server.PagerResponderInjectNextLinks(newListByDatabasePager, req, func(page *armsql.ManagedDatabaseColumnsClientListByDatabaseResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByDatabasePager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		m.newListByDatabasePager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByDatabasePager) {
		m.newListByDatabasePager.remove(req)
	}
	return resp, nil
}

func (m *ManagedDatabaseColumnsServerTransport) dispatchNewListByTablePager(req *http.Request) (*http.Response, error) {
	if m.srv.NewListByTablePager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByTablePager not implemented")}
	}
	newListByTablePager := m.newListByTablePager.get(req)
	if newListByTablePager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Sql/managedInstances/(?P<managedInstanceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P<databaseName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/schemas/(?P<schemaName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tables/(?P<tableName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/columns`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 7 {
			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
		}
		managedInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedInstanceName")])
		if err != nil {
			return nil, err
		}
		databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")])
		if err != nil {
			return nil, err
		}
		schemaNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("schemaName")])
		if err != nil {
			return nil, err
		}
		tableNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("tableName")])
		if err != nil {
			return nil, err
		}
		filterUnescaped, err := url.QueryUnescape(qp.Get("$filter"))
		if err != nil {
			return nil, err
		}
		filterParam := getOptional(filterUnescaped)
		var options *armsql.ManagedDatabaseColumnsClientListByTableOptions
		if filterParam != nil {
			options = &armsql.ManagedDatabaseColumnsClientListByTableOptions{
				Filter: filterParam,
			}
		}
		resp := m.srv.NewListByTablePager(resourceGroupNameParam, managedInstanceNameParam, databaseNameParam, schemaNameParam, tableNameParam, options)
		newListByTablePager = &resp
		m.newListByTablePager.add(req, newListByTablePager)
		server.PagerResponderInjectNextLinks(newListByTablePager, req, func(page *armsql.ManagedDatabaseColumnsClientListByTableResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByTablePager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		m.newListByTablePager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByTablePager) {
		m.newListByTablePager.remove(req)
	}
	return resp, nil
}

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