//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 armmigrationdiscoverysap

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// SapInstancesClient contains the methods for the SapInstances group.
// Don't use this type directly, use NewSapInstancesClient() instead.
type SapInstancesClient struct {
	internal       *arm.Client
	subscriptionID string
}

// NewSapInstancesClient creates a new instance of SapInstancesClient with the specified values.
//   - subscriptionID - The ID of the target subscription.
//   - credential - used to authorize requests. Usually a credential from azidentity.
//   - options - pass nil to accept the default values.
func NewSapInstancesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SapInstancesClient, error) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &SapInstancesClient{
		subscriptionID: subscriptionID,
		internal:       cl,
	}
	return client, nil
}

// BeginCreate - Creates the SAP Instance resource.
// This will be used by service only. PUT operation on this resource by end user will return a Bad Request error.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-10-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - sapDiscoverySiteName - The name of the discovery site resource for SAP Migration.
//   - sapInstanceName - The name of SAP Instance resource for SAP Migration.
//   - resource - Resource create parameters.
//   - options - SapInstancesClientBeginCreateOptions contains the optional parameters for the SapInstancesClient.BeginCreate
//     method.
func (client *SapInstancesClient) BeginCreate(ctx context.Context, resourceGroupName string, sapDiscoverySiteName string, sapInstanceName string, resource SAPInstance, options *SapInstancesClientBeginCreateOptions) (*runtime.Poller[SapInstancesClientCreateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.create(ctx, resourceGroupName, sapDiscoverySiteName, sapInstanceName, resource, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SapInstancesClientCreateResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SapInstancesClientCreateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Create - Creates the SAP Instance resource.
// This will be used by service only. PUT operation on this resource by end user will return a Bad Request error.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-10-01-preview
func (client *SapInstancesClient) create(ctx context.Context, resourceGroupName string, sapDiscoverySiteName string, sapInstanceName string, resource SAPInstance, options *SapInstancesClientBeginCreateOptions) (*http.Response, error) {
	var err error
	const operationName = "SapInstancesClient.BeginCreate"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.createCreateRequest(ctx, resourceGroupName, sapDiscoverySiteName, sapInstanceName, resource, options)
	if err != nil {
		return nil, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// createCreateRequest creates the Create request.
func (client *SapInstancesClient) createCreateRequest(ctx context.Context, resourceGroupName string, sapDiscoverySiteName string, sapInstanceName string, resource SAPInstance, options *SapInstancesClientBeginCreateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Workloads/sapDiscoverySites/{sapDiscoverySiteName}/sapInstances/{sapInstanceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if sapDiscoverySiteName == "" {
		return nil, errors.New("parameter sapDiscoverySiteName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{sapDiscoverySiteName}", url.PathEscape(sapDiscoverySiteName))
	if sapInstanceName == "" {
		return nil, errors.New("parameter sapInstanceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{sapInstanceName}", url.PathEscape(sapInstanceName))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2023-10-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, resource); err != nil {
		return nil, err
	}
	return req, nil
}

// BeginDelete - Deletes the SAP Instance resource.
// This will be used by service only. Delete operation on this resource by end user will return a Bad Request error. You can
// delete the parent resource, which is the SAP Migration discovery site
// resource, using the delete operation on it.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-10-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - sapDiscoverySiteName - The name of the discovery site resource for SAP Migration.
//   - sapInstanceName - The name of SAP Instance resource for SAP Migration.
//   - options - SapInstancesClientBeginDeleteOptions contains the optional parameters for the SapInstancesClient.BeginDelete
//     method.
func (client *SapInstancesClient) BeginDelete(ctx context.Context, resourceGroupName string, sapDiscoverySiteName string, sapInstanceName string, options *SapInstancesClientBeginDeleteOptions) (*runtime.Poller[SapInstancesClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, sapDiscoverySiteName, sapInstanceName, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SapInstancesClientDeleteResponse]{
			FinalStateVia: runtime.FinalStateViaLocation,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SapInstancesClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Deletes the SAP Instance resource.
// This will be used by service only. Delete operation on this resource by end user will return a Bad Request error. You can
// delete the parent resource, which is the SAP Migration discovery site
// resource, using the delete operation on it.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-10-01-preview
func (client *SapInstancesClient) deleteOperation(ctx context.Context, resourceGroupName string, sapDiscoverySiteName string, sapInstanceName string, options *SapInstancesClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "SapInstancesClient.BeginDelete"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.deleteCreateRequest(ctx, resourceGroupName, sapDiscoverySiteName, sapInstanceName, options)
	if err != nil {
		return nil, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// deleteCreateRequest creates the Delete request.
func (client *SapInstancesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, sapDiscoverySiteName string, sapInstanceName string, options *SapInstancesClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Workloads/sapDiscoverySites/{sapDiscoverySiteName}/sapInstances/{sapInstanceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if sapDiscoverySiteName == "" {
		return nil, errors.New("parameter sapDiscoverySiteName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{sapDiscoverySiteName}", url.PathEscape(sapDiscoverySiteName))
	if sapInstanceName == "" {
		return nil, errors.New("parameter sapInstanceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{sapInstanceName}", url.PathEscape(sapInstanceName))
	req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2023-10-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Gets the SAP Instance resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-10-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - sapDiscoverySiteName - The name of the discovery site resource for SAP Migration.
//   - sapInstanceName - The name of SAP Instance resource for SAP Migration.
//   - options - SapInstancesClientGetOptions contains the optional parameters for the SapInstancesClient.Get method.
func (client *SapInstancesClient) Get(ctx context.Context, resourceGroupName string, sapDiscoverySiteName string, sapInstanceName string, options *SapInstancesClientGetOptions) (SapInstancesClientGetResponse, error) {
	var err error
	const operationName = "SapInstancesClient.Get"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.getCreateRequest(ctx, resourceGroupName, sapDiscoverySiteName, sapInstanceName, options)
	if err != nil {
		return SapInstancesClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SapInstancesClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return SapInstancesClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *SapInstancesClient) getCreateRequest(ctx context.Context, resourceGroupName string, sapDiscoverySiteName string, sapInstanceName string, options *SapInstancesClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Workloads/sapDiscoverySites/{sapDiscoverySiteName}/sapInstances/{sapInstanceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if sapDiscoverySiteName == "" {
		return nil, errors.New("parameter sapDiscoverySiteName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{sapDiscoverySiteName}", url.PathEscape(sapDiscoverySiteName))
	if sapInstanceName == "" {
		return nil, errors.New("parameter sapInstanceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{sapInstanceName}", url.PathEscape(sapInstanceName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2023-10-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *SapInstancesClient) getHandleResponse(resp *http.Response) (SapInstancesClientGetResponse, error) {
	result := SapInstancesClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.SAPInstance); err != nil {
		return SapInstancesClientGetResponse{}, err
	}
	return result, nil
}

// NewListBySapDiscoverySitePager - Lists the SAP Instance resources for the given SAP Migration discovery site resource.
//
// Generated from API version 2023-10-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - sapDiscoverySiteName - The name of the discovery site resource for SAP Migration.
//   - options - SapInstancesClientListBySapDiscoverySiteOptions contains the optional parameters for the SapInstancesClient.NewListBySapDiscoverySitePager
//     method.
func (client *SapInstancesClient) NewListBySapDiscoverySitePager(resourceGroupName string, sapDiscoverySiteName string, options *SapInstancesClientListBySapDiscoverySiteOptions) *runtime.Pager[SapInstancesClientListBySapDiscoverySiteResponse] {
	return runtime.NewPager(runtime.PagingHandler[SapInstancesClientListBySapDiscoverySiteResponse]{
		More: func(page SapInstancesClientListBySapDiscoverySiteResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *SapInstancesClientListBySapDiscoverySiteResponse) (SapInstancesClientListBySapDiscoverySiteResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SapInstancesClient.NewListBySapDiscoverySitePager")
			nextLink := ""
			if page != nil {
				nextLink = *page.NextLink
			}
			resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
				return client.listBySapDiscoverySiteCreateRequest(ctx, resourceGroupName, sapDiscoverySiteName, options)
			}, nil)
			if err != nil {
				return SapInstancesClientListBySapDiscoverySiteResponse{}, err
			}
			return client.listBySapDiscoverySiteHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listBySapDiscoverySiteCreateRequest creates the ListBySapDiscoverySite request.
func (client *SapInstancesClient) listBySapDiscoverySiteCreateRequest(ctx context.Context, resourceGroupName string, sapDiscoverySiteName string, options *SapInstancesClientListBySapDiscoverySiteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Workloads/sapDiscoverySites/{sapDiscoverySiteName}/sapInstances"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if sapDiscoverySiteName == "" {
		return nil, errors.New("parameter sapDiscoverySiteName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{sapDiscoverySiteName}", url.PathEscape(sapDiscoverySiteName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2023-10-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listBySapDiscoverySiteHandleResponse handles the ListBySapDiscoverySite response.
func (client *SapInstancesClient) listBySapDiscoverySiteHandleResponse(resp *http.Response) (SapInstancesClientListBySapDiscoverySiteResponse, error) {
	result := SapInstancesClientListBySapDiscoverySiteResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.SAPInstanceListResult); err != nil {
		return SapInstancesClientListBySapDiscoverySiteResponse{}, err
	}
	return result, nil
}

// Update - Updates the SAP Instance resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-10-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - sapDiscoverySiteName - The name of the discovery site resource for SAP Migration.
//   - sapInstanceName - The name of SAP Instance resource for SAP Migration.
//   - properties - The resource properties to be updated.
//   - options - SapInstancesClientUpdateOptions contains the optional parameters for the SapInstancesClient.Update method.
func (client *SapInstancesClient) Update(ctx context.Context, resourceGroupName string, sapDiscoverySiteName string, sapInstanceName string, properties SAPInstanceTagsUpdate, options *SapInstancesClientUpdateOptions) (SapInstancesClientUpdateResponse, error) {
	var err error
	const operationName = "SapInstancesClient.Update"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.updateCreateRequest(ctx, resourceGroupName, sapDiscoverySiteName, sapInstanceName, properties, options)
	if err != nil {
		return SapInstancesClientUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SapInstancesClientUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return SapInstancesClientUpdateResponse{}, err
	}
	resp, err := client.updateHandleResponse(httpResp)
	return resp, err
}

// updateCreateRequest creates the Update request.
func (client *SapInstancesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, sapDiscoverySiteName string, sapInstanceName string, properties SAPInstanceTagsUpdate, options *SapInstancesClientUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Workloads/sapDiscoverySites/{sapDiscoverySiteName}/sapInstances/{sapInstanceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if sapDiscoverySiteName == "" {
		return nil, errors.New("parameter sapDiscoverySiteName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{sapDiscoverySiteName}", url.PathEscape(sapDiscoverySiteName))
	if sapInstanceName == "" {
		return nil, errors.New("parameter sapInstanceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{sapInstanceName}", url.PathEscape(sapInstanceName))
	req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2023-10-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, properties); err != nil {
		return nil, err
	}
	return req, nil
}

// updateHandleResponse handles the Update response.
func (client *SapInstancesClient) updateHandleResponse(resp *http.Response) (SapInstancesClientUpdateResponse, error) {
	result := SapInstancesClientUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.SAPInstance); err != nil {
		return SapInstancesClientUpdateResponse{}, err
	}
	return result, nil
}
