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

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

// GovernanceRulesClient contains the methods for the GovernanceRules group.
// Don't use this type directly, use NewGovernanceRulesClient() instead.
type GovernanceRulesClient struct {
	internal *arm.Client
}

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

// CreateOrUpdate - Creates or updates a governance rule over a given scope
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-01-01-preview
//   - scope - The scope of the Governance rules. Valid scopes are: management group (format: 'providers/Microsoft.Management/managementGroups/{managementGroup}'),
//     subscription (format:
//     'subscriptions/{subscriptionId}'), or security connector (format:
//     'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/securityConnectors/{securityConnectorName})'
//   - ruleID - The governance rule key - unique key for the standard governance rule (GUID)
//   - governanceRule - Governance rule over a given scope
//   - options - GovernanceRulesClientCreateOrUpdateOptions contains the optional parameters for the GovernanceRulesClient.CreateOrUpdate
//     method.
func (client *GovernanceRulesClient) CreateOrUpdate(ctx context.Context, scope string, ruleID string, governanceRule GovernanceRule, options *GovernanceRulesClientCreateOrUpdateOptions) (GovernanceRulesClientCreateOrUpdateResponse, error) {
	var err error
	const operationName = "GovernanceRulesClient.CreateOrUpdate"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.createOrUpdateCreateRequest(ctx, scope, ruleID, governanceRule, options)
	if err != nil {
		return GovernanceRulesClientCreateOrUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return GovernanceRulesClientCreateOrUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return GovernanceRulesClientCreateOrUpdateResponse{}, err
	}
	resp, err := client.createOrUpdateHandleResponse(httpResp)
	return resp, err
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *GovernanceRulesClient) createOrUpdateCreateRequest(ctx context.Context, scope string, ruleID string, governanceRule GovernanceRule, options *GovernanceRulesClientCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/{scope}/providers/Microsoft.Security/governanceRules/{ruleId}"
	if scope == "" {
		return nil, errors.New("parameter scope cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{scope}", url.PathEscape(scope))
	if ruleID == "" {
		return nil, errors.New("parameter ruleID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{ruleId}", url.PathEscape(ruleID))
	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", "2022-01-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, governanceRule); err != nil {
		return nil, err
	}
	return req, nil
}

// createOrUpdateHandleResponse handles the CreateOrUpdate response.
func (client *GovernanceRulesClient) createOrUpdateHandleResponse(resp *http.Response) (GovernanceRulesClientCreateOrUpdateResponse, error) {
	result := GovernanceRulesClientCreateOrUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.GovernanceRule); err != nil {
		return GovernanceRulesClientCreateOrUpdateResponse{}, err
	}
	return result, nil
}

// BeginDelete - Delete a Governance rule over a given scope
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-01-01-preview
//   - scope - The scope of the Governance rules. Valid scopes are: management group (format: 'providers/Microsoft.Management/managementGroups/{managementGroup}'),
//     subscription (format:
//     'subscriptions/{subscriptionId}'), or security connector (format:
//     'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/securityConnectors/{securityConnectorName})'
//   - ruleID - The governance rule key - unique key for the standard governance rule (GUID)
//   - options - GovernanceRulesClientBeginDeleteOptions contains the optional parameters for the GovernanceRulesClient.BeginDelete
//     method.
func (client *GovernanceRulesClient) BeginDelete(ctx context.Context, scope string, ruleID string, options *GovernanceRulesClientBeginDeleteOptions) (*runtime.Poller[GovernanceRulesClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, scope, ruleID, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GovernanceRulesClientDeleteResponse]{
			FinalStateVia: runtime.FinalStateViaLocation,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GovernanceRulesClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Delete a Governance rule over a given scope
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-01-01-preview
func (client *GovernanceRulesClient) deleteOperation(ctx context.Context, scope string, ruleID string, options *GovernanceRulesClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "GovernanceRulesClient.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, scope, ruleID, 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 *GovernanceRulesClient) deleteCreateRequest(ctx context.Context, scope string, ruleID string, options *GovernanceRulesClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/{scope}/providers/Microsoft.Security/governanceRules/{ruleId}"
	if scope == "" {
		return nil, errors.New("parameter scope cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{scope}", url.PathEscape(scope))
	if ruleID == "" {
		return nil, errors.New("parameter ruleID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{ruleId}", url.PathEscape(ruleID))
	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", "2022-01-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	return req, nil
}

// BeginExecute - Execute a governance rule
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-01-01-preview
//   - scope - The scope of the Governance rules. Valid scopes are: management group (format: 'providers/Microsoft.Management/managementGroups/{managementGroup}'),
//     subscription (format:
//     'subscriptions/{subscriptionId}'), or security connector (format:
//     'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/securityConnectors/{securityConnectorName})'
//   - ruleID - The governance rule key - unique key for the standard governance rule (GUID)
//   - options - GovernanceRulesClientBeginExecuteOptions contains the optional parameters for the GovernanceRulesClient.BeginExecute
//     method.
func (client *GovernanceRulesClient) BeginExecute(ctx context.Context, scope string, ruleID string, options *GovernanceRulesClientBeginExecuteOptions) (*runtime.Poller[GovernanceRulesClientExecuteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.execute(ctx, scope, ruleID, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GovernanceRulesClientExecuteResponse]{
			FinalStateVia: runtime.FinalStateViaLocation,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GovernanceRulesClientExecuteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Execute - Execute a governance rule
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-01-01-preview
func (client *GovernanceRulesClient) execute(ctx context.Context, scope string, ruleID string, options *GovernanceRulesClientBeginExecuteOptions) (*http.Response, error) {
	var err error
	const operationName = "GovernanceRulesClient.BeginExecute"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.executeCreateRequest(ctx, scope, ruleID, 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.StatusAccepted) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// executeCreateRequest creates the Execute request.
func (client *GovernanceRulesClient) executeCreateRequest(ctx context.Context, scope string, ruleID string, options *GovernanceRulesClientBeginExecuteOptions) (*policy.Request, error) {
	urlPath := "/{scope}/providers/Microsoft.Security/governanceRules/{ruleId}/execute"
	if scope == "" {
		return nil, errors.New("parameter scope cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{scope}", url.PathEscape(scope))
	if ruleID == "" {
		return nil, errors.New("parameter ruleID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{ruleId}", url.PathEscape(ruleID))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-01-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if options != nil && options.ExecuteGovernanceRuleParams != nil {
		if err := runtime.MarshalAsJSON(req, *options.ExecuteGovernanceRuleParams); err != nil {
			return nil, err
		}
		return req, nil
	}
	return req, nil
}

// Get - Get a specific governance rule for the requested scope by ruleId
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-01-01-preview
//   - scope - The scope of the Governance rules. Valid scopes are: management group (format: 'providers/Microsoft.Management/managementGroups/{managementGroup}'),
//     subscription (format:
//     'subscriptions/{subscriptionId}'), or security connector (format:
//     'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/securityConnectors/{securityConnectorName})'
//   - ruleID - The governance rule key - unique key for the standard governance rule (GUID)
//   - options - GovernanceRulesClientGetOptions contains the optional parameters for the GovernanceRulesClient.Get method.
func (client *GovernanceRulesClient) Get(ctx context.Context, scope string, ruleID string, options *GovernanceRulesClientGetOptions) (GovernanceRulesClientGetResponse, error) {
	var err error
	const operationName = "GovernanceRulesClient.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, scope, ruleID, options)
	if err != nil {
		return GovernanceRulesClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return GovernanceRulesClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return GovernanceRulesClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *GovernanceRulesClient) getCreateRequest(ctx context.Context, scope string, ruleID string, options *GovernanceRulesClientGetOptions) (*policy.Request, error) {
	urlPath := "/{scope}/providers/Microsoft.Security/governanceRules/{ruleId}"
	if scope == "" {
		return nil, errors.New("parameter scope cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{scope}", url.PathEscape(scope))
	if ruleID == "" {
		return nil, errors.New("parameter ruleID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{ruleId}", url.PathEscape(ruleID))
	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", "2022-01-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 *GovernanceRulesClient) getHandleResponse(resp *http.Response) (GovernanceRulesClientGetResponse, error) {
	result := GovernanceRulesClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.GovernanceRule); err != nil {
		return GovernanceRulesClientGetResponse{}, err
	}
	return result, nil
}

// NewListPager - Get a list of all relevant governance rules over a scope
//
// Generated from API version 2022-01-01-preview
//   - scope - The scope of the Governance rules. Valid scopes are: management group (format: 'providers/Microsoft.Management/managementGroups/{managementGroup}'),
//     subscription (format:
//     'subscriptions/{subscriptionId}'), or security connector (format:
//     'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/securityConnectors/{securityConnectorName})'
//   - options - GovernanceRulesClientListOptions contains the optional parameters for the GovernanceRulesClient.NewListPager
//     method.
func (client *GovernanceRulesClient) NewListPager(scope string, options *GovernanceRulesClientListOptions) *runtime.Pager[GovernanceRulesClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[GovernanceRulesClientListResponse]{
		More: func(page GovernanceRulesClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *GovernanceRulesClientListResponse) (GovernanceRulesClientListResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GovernanceRulesClient.NewListPager")
			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.listCreateRequest(ctx, scope, options)
			}, nil)
			if err != nil {
				return GovernanceRulesClientListResponse{}, err
			}
			return client.listHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listCreateRequest creates the List request.
func (client *GovernanceRulesClient) listCreateRequest(ctx context.Context, scope string, options *GovernanceRulesClientListOptions) (*policy.Request, error) {
	urlPath := "/{scope}/providers/Microsoft.Security/governanceRules"
	if scope == "" {
		return nil, errors.New("parameter scope cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{scope}", url.PathEscape(scope))
	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", "2022-01-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listHandleResponse handles the List response.
func (client *GovernanceRulesClient) listHandleResponse(resp *http.Response) (GovernanceRulesClientListResponse, error) {
	result := GovernanceRulesClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.GovernanceRuleList); err != nil {
		return GovernanceRulesClientListResponse{}, err
	}
	return result, nil
}

// OperationResults - Get governance rules long run operation result for the requested scope by ruleId and operationId
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-01-01-preview
//   - scope - The scope of the Governance rules. Valid scopes are: management group (format: 'providers/Microsoft.Management/managementGroups/{managementGroup}'),
//     subscription (format:
//     'subscriptions/{subscriptionId}'), or security connector (format:
//     'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/securityConnectors/{securityConnectorName})'
//   - ruleID - The governance rule key - unique key for the standard governance rule (GUID)
//   - operationID - The governance rule long running operation unique key
//   - options - GovernanceRulesClientOperationResultsOptions contains the optional parameters for the GovernanceRulesClient.OperationResults
//     method.
func (client *GovernanceRulesClient) OperationResults(ctx context.Context, scope string, ruleID string, operationID string, options *GovernanceRulesClientOperationResultsOptions) (GovernanceRulesClientOperationResultsResponse, error) {
	var err error
	const operationName = "GovernanceRulesClient.OperationResults"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.operationResultsCreateRequest(ctx, scope, ruleID, operationID, options)
	if err != nil {
		return GovernanceRulesClientOperationResultsResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return GovernanceRulesClientOperationResultsResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
		err = runtime.NewResponseError(httpResp)
		return GovernanceRulesClientOperationResultsResponse{}, err
	}
	resp, err := client.operationResultsHandleResponse(httpResp)
	return resp, err
}

// operationResultsCreateRequest creates the OperationResults request.
func (client *GovernanceRulesClient) operationResultsCreateRequest(ctx context.Context, scope string, ruleID string, operationID string, options *GovernanceRulesClientOperationResultsOptions) (*policy.Request, error) {
	urlPath := "/{scope}/providers/Microsoft.Security/governanceRules/{ruleId}/operationResults/{operationId}"
	if scope == "" {
		return nil, errors.New("parameter scope cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{scope}", url.PathEscape(scope))
	if ruleID == "" {
		return nil, errors.New("parameter ruleID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{ruleId}", url.PathEscape(ruleID))
	if operationID == "" {
		return nil, errors.New("parameter operationID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{operationId}", url.PathEscape(operationID))
	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", "2022-01-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// operationResultsHandleResponse handles the OperationResults response.
func (client *GovernanceRulesClient) operationResultsHandleResponse(resp *http.Response) (GovernanceRulesClientOperationResultsResponse, error) {
	result := GovernanceRulesClientOperationResultsResponse{}
	if val := resp.Header.Get("location"); val != "" {
		result.Location = &val
	}
	if err := runtime.UnmarshalAsJSON(resp, &result.OperationResultAutoGenerated); err != nil {
		return GovernanceRulesClientOperationResultsResponse{}, err
	}
	return result, nil
}
