//go:build go1.18
// +build go1.18

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

// ResourceLinksServer is a fake server for instances of the armlinks.ResourceLinksClient type.
type ResourceLinksServer struct {
	// CreateOrUpdate is the fake for method ResourceLinksClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrUpdate func(ctx context.Context, linkID string, parameters armlinks.ResourceLink, options *armlinks.ResourceLinksClientCreateOrUpdateOptions) (resp azfake.Responder[armlinks.ResourceLinksClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method ResourceLinksClient.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, linkID string, options *armlinks.ResourceLinksClientDeleteOptions) (resp azfake.Responder[armlinks.ResourceLinksClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method ResourceLinksClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, linkID string, options *armlinks.ResourceLinksClientGetOptions) (resp azfake.Responder[armlinks.ResourceLinksClientGetResponse], errResp azfake.ErrorResponder)

	// NewListAtSourceScopePager is the fake for method ResourceLinksClient.NewListAtSourceScopePager
	// HTTP status codes to indicate success: http.StatusOK
	NewListAtSourceScopePager func(scope string, options *armlinks.ResourceLinksClientListAtSourceScopeOptions) (resp azfake.PagerResponder[armlinks.ResourceLinksClientListAtSourceScopeResponse])

	// NewListAtSubscriptionPager is the fake for method ResourceLinksClient.NewListAtSubscriptionPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListAtSubscriptionPager func(options *armlinks.ResourceLinksClientListAtSubscriptionOptions) (resp azfake.PagerResponder[armlinks.ResourceLinksClientListAtSubscriptionResponse])
}

// NewResourceLinksServerTransport creates a new instance of ResourceLinksServerTransport with the provided implementation.
// The returned ResourceLinksServerTransport instance is connected to an instance of armlinks.ResourceLinksClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewResourceLinksServerTransport(srv *ResourceLinksServer) *ResourceLinksServerTransport {
	return &ResourceLinksServerTransport{
		srv:                        srv,
		newListAtSourceScopePager:  newTracker[azfake.PagerResponder[armlinks.ResourceLinksClientListAtSourceScopeResponse]](),
		newListAtSubscriptionPager: newTracker[azfake.PagerResponder[armlinks.ResourceLinksClientListAtSubscriptionResponse]](),
	}
}

// ResourceLinksServerTransport connects instances of armlinks.ResourceLinksClient to instances of ResourceLinksServer.
// Don't use this type directly, use NewResourceLinksServerTransport instead.
type ResourceLinksServerTransport struct {
	srv                        *ResourceLinksServer
	newListAtSourceScopePager  *tracker[azfake.PagerResponder[armlinks.ResourceLinksClientListAtSourceScopeResponse]]
	newListAtSubscriptionPager *tracker[azfake.PagerResponder[armlinks.ResourceLinksClientListAtSubscriptionResponse]]
}

// Do implements the policy.Transporter interface for ResourceLinksServerTransport.
func (r *ResourceLinksServerTransport) 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")}
	}

	var resp *http.Response
	var err error

	switch method {
	case "ResourceLinksClient.CreateOrUpdate":
		resp, err = r.dispatchCreateOrUpdate(req)
	case "ResourceLinksClient.Delete":
		resp, err = r.dispatchDelete(req)
	case "ResourceLinksClient.Get":
		resp, err = r.dispatchGet(req)
	case "ResourceLinksClient.NewListAtSourceScopePager":
		resp, err = r.dispatchNewListAtSourceScopePager(req)
	case "ResourceLinksClient.NewListAtSubscriptionPager":
		resp, err = r.dispatchNewListAtSubscriptionPager(req)
	default:
		err = fmt.Errorf("unhandled API %s", method)
	}

	if err != nil {
		return nil, err
	}

	return resp, nil
}

func (r *ResourceLinksServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if r.srv.CreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")}
	}
	const regexStr = `/(?P<linkId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 1 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armlinks.ResourceLink](req)
	if err != nil {
		return nil, err
	}
	linkIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("linkId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := r.srv.CreateOrUpdate(req.Context(), linkIDParam, 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).ResourceLink, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (r *ResourceLinksServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if r.srv.Delete == nil {
		return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")}
	}
	const regexStr = `/(?P<linkId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 1 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	linkIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("linkId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := r.srv.Delete(req.Context(), linkIDParam, 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 (r *ResourceLinksServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if r.srv.Get == nil {
		return nil, &nonRetriableError{errors.New("fake for method Get not implemented")}
	}
	const regexStr = `/(?P<linkId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 1 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	linkIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("linkId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := r.srv.Get(req.Context(), linkIDParam, 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).ResourceLink, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (r *ResourceLinksServerTransport) dispatchNewListAtSourceScopePager(req *http.Request) (*http.Response, error) {
	if r.srv.NewListAtSourceScopePager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListAtSourceScopePager not implemented")}
	}
	newListAtSourceScopePager := r.newListAtSourceScopePager.get(req)
	if newListAtSourceScopePager == nil {
		const regexStr = `/(?P<scope>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Resources/links`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 1 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		qp := req.URL.Query()
		scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")])
		if err != nil {
			return nil, err
		}
		filterUnescaped, err := url.QueryUnescape(qp.Get("$filter"))
		if err != nil {
			return nil, err
		}
		filterParam := getOptional(filterUnescaped)
		var options *armlinks.ResourceLinksClientListAtSourceScopeOptions
		if filterParam != nil {
			options = &armlinks.ResourceLinksClientListAtSourceScopeOptions{
				Filter: filterParam,
			}
		}
		resp := r.srv.NewListAtSourceScopePager(scopeParam, options)
		newListAtSourceScopePager = &resp
		r.newListAtSourceScopePager.add(req, newListAtSourceScopePager)
		server.PagerResponderInjectNextLinks(newListAtSourceScopePager, req, func(page *armlinks.ResourceLinksClientListAtSourceScopeResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListAtSourceScopePager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		r.newListAtSourceScopePager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListAtSourceScopePager) {
		r.newListAtSourceScopePager.remove(req)
	}
	return resp, nil
}

func (r *ResourceLinksServerTransport) dispatchNewListAtSubscriptionPager(req *http.Request) (*http.Response, error) {
	if r.srv.NewListAtSubscriptionPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListAtSubscriptionPager not implemented")}
	}
	newListAtSubscriptionPager := r.newListAtSubscriptionPager.get(req)
	if newListAtSubscriptionPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Resources/links`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 1 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		qp := req.URL.Query()
		filterUnescaped, err := url.QueryUnescape(qp.Get("$filter"))
		if err != nil {
			return nil, err
		}
		filterParam := getOptional(filterUnescaped)
		var options *armlinks.ResourceLinksClientListAtSubscriptionOptions
		if filterParam != nil {
			options = &armlinks.ResourceLinksClientListAtSubscriptionOptions{
				Filter: filterParam,
			}
		}
		resp := r.srv.NewListAtSubscriptionPager(options)
		newListAtSubscriptionPager = &resp
		r.newListAtSubscriptionPager.add(req, newListAtSubscriptionPager)
		server.PagerResponderInjectNextLinks(newListAtSubscriptionPager, req, func(page *armlinks.ResourceLinksClientListAtSubscriptionResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListAtSubscriptionPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		r.newListAtSubscriptionPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListAtSubscriptionPager) {
		r.newListAtSubscriptionPager.remove(req)
	}
	return resp, nil
}
