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

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

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

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

// NewDatabaseColumnsServerTransport creates a new instance of DatabaseColumnsServerTransport with the provided implementation.
// The returned DatabaseColumnsServerTransport instance is connected to an instance of armsql.DatabaseColumnsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewDatabaseColumnsServerTransport(srv *DatabaseColumnsServer) *DatabaseColumnsServerTransport {
	return &DatabaseColumnsServerTransport{
		srv:                    srv,
		newListByDatabasePager: newTracker[azfake.PagerResponder[armsql.DatabaseColumnsClientListByDatabaseResponse]](),
		newListByTablePager:    newTracker[azfake.PagerResponder[armsql.DatabaseColumnsClientListByTableResponse]](),
	}
}

// DatabaseColumnsServerTransport connects instances of armsql.DatabaseColumnsClient to instances of DatabaseColumnsServer.
// Don't use this type directly, use NewDatabaseColumnsServerTransport instead.
type DatabaseColumnsServerTransport struct {
	srv                    *DatabaseColumnsServer
	newListByDatabasePager *tracker[azfake.PagerResponder[armsql.DatabaseColumnsClientListByDatabaseResponse]]
	newListByTablePager    *tracker[azfake.PagerResponder[armsql.DatabaseColumnsClientListByTableResponse]]
}

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

func (d *DatabaseColumnsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result, 1)
	go func() {
		var intercepted bool
		var res result
		if databaseColumnsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = databaseColumnsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "DatabaseColumnsClient.Get":
				res.resp, res.err = d.dispatchGet(req)
			case "DatabaseColumnsClient.NewListByDatabasePager":
				res.resp, res.err = d.dispatchNewListByDatabasePager(req)
			case "DatabaseColumnsClient.NewListByTablePager":
				res.resp, res.err = d.dispatchNewListByTablePager(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 (d *DatabaseColumnsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if d.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/servers/(?P<serverName>[!#&$-;=?-\[\]_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
	}
	serverNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serverName")])
	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 := d.srv.Get(req.Context(), resourceGroupNameParam, serverNameParam, databaseNameParam, schemaNameParam, tableNameParam, columnNameParam, 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).DatabaseColumn, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (d *DatabaseColumnsServerTransport) dispatchNewListByDatabasePager(req *http.Request) (*http.Response, error) {
	if d.srv.NewListByDatabasePager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByDatabasePager not implemented")}
	}
	newListByDatabasePager := d.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/servers/(?P<serverName>[!#&$-;=?-\[\]_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
		}
		serverNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serverName")])
		if err != nil {
			return nil, err
		}
		databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")])
		if err != nil {
			return nil, err
		}
		skiptokenParam := getOptional(qp.Get("$skiptoken"))
		var options *armsql.DatabaseColumnsClientListByDatabaseOptions
		if len(qp["schema"]) > 0 || len(qp["table"]) > 0 || len(qp["column"]) > 0 || len(qp["orderBy"]) > 0 || skiptokenParam != nil {
			options = &armsql.DatabaseColumnsClientListByDatabaseOptions{
				Schema:    qp["schema"],
				Table:     qp["table"],
				Column:    qp["column"],
				OrderBy:   qp["orderBy"],
				Skiptoken: skiptokenParam,
			}
		}
		resp := d.srv.NewListByDatabasePager(resourceGroupNameParam, serverNameParam, databaseNameParam, options)
		newListByDatabasePager = &resp
		d.newListByDatabasePager.add(req, newListByDatabasePager)
		server.PagerResponderInjectNextLinks(newListByDatabasePager, req, func(page *armsql.DatabaseColumnsClientListByDatabaseResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByDatabasePager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		d.newListByDatabasePager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByDatabasePager) {
		d.newListByDatabasePager.remove(req)
	}
	return resp, nil
}

func (d *DatabaseColumnsServerTransport) dispatchNewListByTablePager(req *http.Request) (*http.Response, error) {
	if d.srv.NewListByTablePager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByTablePager not implemented")}
	}
	newListByTablePager := d.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/servers/(?P<serverName>[!#&$-;=?-\[\]_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
		}
		serverNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serverName")])
		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
		}
		filterParam := getOptional(qp.Get("$filter"))
		var options *armsql.DatabaseColumnsClientListByTableOptions
		if filterParam != nil {
			options = &armsql.DatabaseColumnsClientListByTableOptions{
				Filter: filterParam,
			}
		}
		resp := d.srv.NewListByTablePager(resourceGroupNameParam, serverNameParam, databaseNameParam, schemaNameParam, tableNameParam, options)
		newListByTablePager = &resp
		d.newListByTablePager.add(req, newListByTablePager)
		server.PagerResponderInjectNextLinks(newListByTablePager, req, func(page *armsql.DatabaseColumnsClientListByTableResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByTablePager, req)
	if err != nil {
		return nil, err
	}
	if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) {
		d.newListByTablePager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByTablePager) {
		d.newListByTablePager.remove(req)
	}
	return resp, nil
}

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