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

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"
)

// RuntimeEnvironmentsClient contains the methods for the RuntimeEnvironments group.
// Don't use this type directly, use NewRuntimeEnvironmentsClient() instead.
//
// Generated from API version 2024-10-23
type RuntimeEnvironmentsClient struct {
	internal       *arm.Client
	subscriptionID string
}

// NewRuntimeEnvironmentsClient creates a new instance of RuntimeEnvironmentsClient with the specified values.
//   - subscriptionID - The ID of the target subscription. The value must be an UUID.
//   - credential - used to authorize requests. Usually a credential from azidentity.
//   - options - Contains optional client configuration. Pass nil to accept the default values.
func NewRuntimeEnvironmentsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RuntimeEnvironmentsClient, error) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &RuntimeEnvironmentsClient{
		subscriptionID: subscriptionID,
		internal:       cl,
	}
	return client, nil
}

// Create - Create or update Runtime Environment
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - automationAccountName - The name of the automation account.
//   - runtimeEnvironmentName - The name of the Runtime Environment.
//   - parameters - Parameters supplied to the create the runtime environment.
//   - options - RuntimeEnvironmentsClientCreateOptions contains the optional parameters for the RuntimeEnvironmentsClient.Create
//     method.
func (client *RuntimeEnvironmentsClient) Create(ctx context.Context, resourceGroupName string, automationAccountName string, runtimeEnvironmentName string, parameters RuntimeEnvironment, options *RuntimeEnvironmentsClientCreateOptions) (RuntimeEnvironmentsClientCreateResponse, error) {
	var err error
	const operationName = "RuntimeEnvironmentsClient.Create"
	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, automationAccountName, runtimeEnvironmentName, parameters, options)
	if err != nil {
		return RuntimeEnvironmentsClientCreateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return RuntimeEnvironmentsClientCreateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return RuntimeEnvironmentsClientCreateResponse{}, err
	}
	resp, err := client.createHandleResponse(httpResp)
	return resp, err
}

// createCreateRequest creates the Create request.
func (client *RuntimeEnvironmentsClient) createCreateRequest(ctx context.Context, resourceGroupName string, automationAccountName string, runtimeEnvironmentName string, parameters RuntimeEnvironment, _ *RuntimeEnvironmentsClientCreateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/runtimeEnvironments/{runtimeEnvironmentName}"
	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 automationAccountName == "" {
		return nil, errors.New("parameter automationAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{automationAccountName}", url.PathEscape(automationAccountName))
	if runtimeEnvironmentName == "" {
		return nil, errors.New("parameter runtimeEnvironmentName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{runtimeEnvironmentName}", url.PathEscape(runtimeEnvironmentName))
	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", version20241023)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	req.Raw().Header["Content-Type"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, parameters); err != nil {
		return nil, err
	}
	return req, nil
}

// createHandleResponse handles the Create response.
func (client *RuntimeEnvironmentsClient) createHandleResponse(resp *http.Response) (RuntimeEnvironmentsClientCreateResponse, error) {
	result := RuntimeEnvironmentsClientCreateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.RuntimeEnvironment); err != nil {
		return RuntimeEnvironmentsClientCreateResponse{}, err
	}
	return result, nil
}

// Delete - Delete the Runtime Environment.
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - automationAccountName - The name of the automation account.
//   - runtimeEnvironmentName - The name of the Runtime Environment.
//   - options - RuntimeEnvironmentsClientDeleteOptions contains the optional parameters for the RuntimeEnvironmentsClient.Delete
//     method.
func (client *RuntimeEnvironmentsClient) Delete(ctx context.Context, resourceGroupName string, automationAccountName string, runtimeEnvironmentName string, options *RuntimeEnvironmentsClientDeleteOptions) (RuntimeEnvironmentsClientDeleteResponse, error) {
	var err error
	const operationName = "RuntimeEnvironmentsClient.Delete"
	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, automationAccountName, runtimeEnvironmentName, options)
	if err != nil {
		return RuntimeEnvironmentsClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return RuntimeEnvironmentsClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return RuntimeEnvironmentsClientDeleteResponse{}, err
	}
	return RuntimeEnvironmentsClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *RuntimeEnvironmentsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, automationAccountName string, runtimeEnvironmentName string, _ *RuntimeEnvironmentsClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/runtimeEnvironments/{runtimeEnvironmentName}"
	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 automationAccountName == "" {
		return nil, errors.New("parameter automationAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{automationAccountName}", url.PathEscape(automationAccountName))
	if runtimeEnvironmentName == "" {
		return nil, errors.New("parameter runtimeEnvironmentName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{runtimeEnvironmentName}", url.PathEscape(runtimeEnvironmentName))
	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", version20241023)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	return req, nil
}

// Get - Get information about the Runtime Environment
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - automationAccountName - The name of the automation account.
//   - runtimeEnvironmentName - The name of the Runtime Environment.
//   - options - RuntimeEnvironmentsClientGetOptions contains the optional parameters for the RuntimeEnvironmentsClient.Get method.
func (client *RuntimeEnvironmentsClient) Get(ctx context.Context, resourceGroupName string, automationAccountName string, runtimeEnvironmentName string, options *RuntimeEnvironmentsClientGetOptions) (RuntimeEnvironmentsClientGetResponse, error) {
	var err error
	const operationName = "RuntimeEnvironmentsClient.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, automationAccountName, runtimeEnvironmentName, options)
	if err != nil {
		return RuntimeEnvironmentsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return RuntimeEnvironmentsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return RuntimeEnvironmentsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *RuntimeEnvironmentsClient) getCreateRequest(ctx context.Context, resourceGroupName string, automationAccountName string, runtimeEnvironmentName string, _ *RuntimeEnvironmentsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/runtimeEnvironments/{runtimeEnvironmentName}"
	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 automationAccountName == "" {
		return nil, errors.New("parameter automationAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{automationAccountName}", url.PathEscape(automationAccountName))
	if runtimeEnvironmentName == "" {
		return nil, errors.New("parameter runtimeEnvironmentName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{runtimeEnvironmentName}", url.PathEscape(runtimeEnvironmentName))
	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", version20241023)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListByAutomationAccountPager - Retrieve a list of RuntimeEnvironments.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - automationAccountName - The name of the automation account.
//   - options - RuntimeEnvironmentsClientListByAutomationAccountOptions contains the optional parameters for the RuntimeEnvironmentsClient.NewListByAutomationAccountPager
//     method.
func (client *RuntimeEnvironmentsClient) NewListByAutomationAccountPager(resourceGroupName string, automationAccountName string, options *RuntimeEnvironmentsClientListByAutomationAccountOptions) *runtime.Pager[RuntimeEnvironmentsClientListByAutomationAccountResponse] {
	return runtime.NewPager(runtime.PagingHandler[RuntimeEnvironmentsClientListByAutomationAccountResponse]{
		More: func(page RuntimeEnvironmentsClientListByAutomationAccountResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *RuntimeEnvironmentsClientListByAutomationAccountResponse) (RuntimeEnvironmentsClientListByAutomationAccountResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RuntimeEnvironmentsClient.NewListByAutomationAccountPager")
			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.listByAutomationAccountCreateRequest(ctx, resourceGroupName, automationAccountName, options)
			}, nil)
			if err != nil {
				return RuntimeEnvironmentsClientListByAutomationAccountResponse{}, err
			}
			return client.listByAutomationAccountHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByAutomationAccountCreateRequest creates the ListByAutomationAccount request.
func (client *RuntimeEnvironmentsClient) listByAutomationAccountCreateRequest(ctx context.Context, resourceGroupName string, automationAccountName string, _ *RuntimeEnvironmentsClientListByAutomationAccountOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/runtimeEnvironments"
	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 automationAccountName == "" {
		return nil, errors.New("parameter automationAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{automationAccountName}", url.PathEscape(automationAccountName))
	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", version20241023)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByAutomationAccountHandleResponse handles the ListByAutomationAccount response.
func (client *RuntimeEnvironmentsClient) listByAutomationAccountHandleResponse(resp *http.Response) (RuntimeEnvironmentsClientListByAutomationAccountResponse, error) {
	result := RuntimeEnvironmentsClientListByAutomationAccountResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.RuntimeEnvironmentListResult); err != nil {
		return RuntimeEnvironmentsClientListByAutomationAccountResponse{}, err
	}
	return result, nil
}

// Update - Update an Runtime Environment.
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - automationAccountName - The name of the automation account.
//   - runtimeEnvironmentName - The name of the Runtime Environment.
//   - parameters - Parameters supplied to the Runtime Environment
//   - options - RuntimeEnvironmentsClientUpdateOptions contains the optional parameters for the RuntimeEnvironmentsClient.Update
//     method.
func (client *RuntimeEnvironmentsClient) Update(ctx context.Context, resourceGroupName string, automationAccountName string, runtimeEnvironmentName string, parameters RuntimeEnvironmentUpdateParameters, options *RuntimeEnvironmentsClientUpdateOptions) (RuntimeEnvironmentsClientUpdateResponse, error) {
	var err error
	const operationName = "RuntimeEnvironmentsClient.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, automationAccountName, runtimeEnvironmentName, parameters, options)
	if err != nil {
		return RuntimeEnvironmentsClientUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return RuntimeEnvironmentsClientUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return RuntimeEnvironmentsClientUpdateResponse{}, err
	}
	resp, err := client.updateHandleResponse(httpResp)
	return resp, err
}

// updateCreateRequest creates the Update request.
func (client *RuntimeEnvironmentsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, automationAccountName string, runtimeEnvironmentName string, parameters RuntimeEnvironmentUpdateParameters, _ *RuntimeEnvironmentsClientUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/runtimeEnvironments/{runtimeEnvironmentName}"
	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 automationAccountName == "" {
		return nil, errors.New("parameter automationAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{automationAccountName}", url.PathEscape(automationAccountName))
	if runtimeEnvironmentName == "" {
		return nil, errors.New("parameter runtimeEnvironmentName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{runtimeEnvironmentName}", url.PathEscape(runtimeEnvironmentName))
	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", version20241023)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	req.Raw().Header["Content-Type"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, parameters); err != nil {
		return nil, err
	}
	return req, nil
}

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