//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/appcomplianceautomation/armappcomplianceautomation"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
)

// SnapshotServer is a fake server for instances of the armappcomplianceautomation.SnapshotClient type.
type SnapshotServer struct {
	// BeginDownload is the fake for method SnapshotClient.BeginDownload
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginDownload func(ctx context.Context, reportName string, snapshotName string, body armappcomplianceautomation.SnapshotDownloadRequest, options *armappcomplianceautomation.SnapshotClientBeginDownloadOptions) (resp azfake.PollerResponder[armappcomplianceautomation.SnapshotClientDownloadResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method SnapshotClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, reportName string, snapshotName string, options *armappcomplianceautomation.SnapshotClientGetOptions) (resp azfake.Responder[armappcomplianceautomation.SnapshotClientGetResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method SnapshotClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(reportName string, options *armappcomplianceautomation.SnapshotClientListOptions) (resp azfake.PagerResponder[armappcomplianceautomation.SnapshotClientListResponse])
}

// NewSnapshotServerTransport creates a new instance of SnapshotServerTransport with the provided implementation.
// The returned SnapshotServerTransport instance is connected to an instance of armappcomplianceautomation.SnapshotClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewSnapshotServerTransport(srv *SnapshotServer) *SnapshotServerTransport {
	return &SnapshotServerTransport{
		srv:           srv,
		beginDownload: newTracker[azfake.PollerResponder[armappcomplianceautomation.SnapshotClientDownloadResponse]](),
		newListPager:  newTracker[azfake.PagerResponder[armappcomplianceautomation.SnapshotClientListResponse]](),
	}
}

// SnapshotServerTransport connects instances of armappcomplianceautomation.SnapshotClient to instances of SnapshotServer.
// Don't use this type directly, use NewSnapshotServerTransport instead.
type SnapshotServerTransport struct {
	srv           *SnapshotServer
	beginDownload *tracker[azfake.PollerResponder[armappcomplianceautomation.SnapshotClientDownloadResponse]]
	newListPager  *tracker[azfake.PagerResponder[armappcomplianceautomation.SnapshotClientListResponse]]
}

// Do implements the policy.Transporter interface for SnapshotServerTransport.
func (s *SnapshotServerTransport) 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 "SnapshotClient.BeginDownload":
		resp, err = s.dispatchBeginDownload(req)
	case "SnapshotClient.Get":
		resp, err = s.dispatchGet(req)
	case "SnapshotClient.NewListPager":
		resp, err = s.dispatchNewListPager(req)
	default:
		err = fmt.Errorf("unhandled API %s", method)
	}

	if err != nil {
		return nil, err
	}

	return resp, nil
}

func (s *SnapshotServerTransport) dispatchBeginDownload(req *http.Request) (*http.Response, error) {
	if s.srv.BeginDownload == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDownload not implemented")}
	}
	beginDownload := s.beginDownload.get(req)
	if beginDownload == nil {
		const regexStr = `/providers/Microsoft\.AppComplianceAutomation/reports/(?P<reportName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/snapshots/(?P<snapshotName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/download`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || len(matches) < 2 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		body, err := server.UnmarshalRequestAsJSON[armappcomplianceautomation.SnapshotDownloadRequest](req)
		if err != nil {
			return nil, err
		}
		reportNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("reportName")])
		if err != nil {
			return nil, err
		}
		snapshotNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("snapshotName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := s.srv.BeginDownload(req.Context(), reportNameParam, snapshotNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDownload = &respr
		s.beginDownload.add(req, beginDownload)
	}

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

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

	return resp, nil
}

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

func (s *SnapshotServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if s.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := s.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/providers/Microsoft\.AppComplianceAutomation/reports/(?P<reportName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/snapshots`
		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()
		skipTokenUnescaped, err := url.QueryUnescape(qp.Get("$skipToken"))
		if err != nil {
			return nil, err
		}
		skipTokenParam := getOptional(skipTokenUnescaped)
		topUnescaped, err := url.QueryUnescape(qp.Get("$top"))
		if err != nil {
			return nil, err
		}
		topParam, err := parseOptional(topUnescaped, func(v string) (int32, error) {
			p, parseErr := strconv.ParseInt(v, 10, 32)
			if parseErr != nil {
				return 0, parseErr
			}
			return int32(p), nil
		})
		if err != nil {
			return nil, err
		}
		selectUnescaped, err := url.QueryUnescape(qp.Get("$select"))
		if err != nil {
			return nil, err
		}
		selectParam := getOptional(selectUnescaped)
		filterUnescaped, err := url.QueryUnescape(qp.Get("$filter"))
		if err != nil {
			return nil, err
		}
		filterParam := getOptional(filterUnescaped)
		orderbyUnescaped, err := url.QueryUnescape(qp.Get("$orderby"))
		if err != nil {
			return nil, err
		}
		orderbyParam := getOptional(orderbyUnescaped)
		offerGUIDUnescaped, err := url.QueryUnescape(qp.Get("offerGuid"))
		if err != nil {
			return nil, err
		}
		offerGUIDParam := getOptional(offerGUIDUnescaped)
		reportCreatorTenantIDUnescaped, err := url.QueryUnescape(qp.Get("reportCreatorTenantId"))
		if err != nil {
			return nil, err
		}
		reportCreatorTenantIDParam := getOptional(reportCreatorTenantIDUnescaped)
		reportNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("reportName")])
		if err != nil {
			return nil, err
		}
		var options *armappcomplianceautomation.SnapshotClientListOptions
		if skipTokenParam != nil || topParam != nil || selectParam != nil || filterParam != nil || orderbyParam != nil || offerGUIDParam != nil || reportCreatorTenantIDParam != nil {
			options = &armappcomplianceautomation.SnapshotClientListOptions{
				SkipToken:             skipTokenParam,
				Top:                   topParam,
				Select:                selectParam,
				Filter:                filterParam,
				Orderby:               orderbyParam,
				OfferGUID:             offerGUIDParam,
				ReportCreatorTenantID: reportCreatorTenantIDParam,
			}
		}
		resp := s.srv.NewListPager(reportNameParam, options)
		newListPager = &resp
		s.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armappcomplianceautomation.SnapshotClientListResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		s.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		s.newListPager.remove(req)
	}
	return resp, nil
}
