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

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"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime"
	"net/http"
	"net/url"
	"strings"
)

// DiscoveryRulesClient contains the methods for the DiscoveryRules group.
// Don't use this type directly, use NewDiscoveryRulesClient() instead.
//
// Generated from API version 2026-05-01-preview
type DiscoveryRulesClient struct {
	internal       *arm.Client
	subscriptionID string
}

// NewDiscoveryRulesClient creates a new instance of DiscoveryRulesClient 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 NewDiscoveryRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DiscoveryRulesClient, error) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &DiscoveryRulesClient{
		subscriptionID: subscriptionID,
		internal:       cl,
	}
	return client, nil
}

// BeginCreateOrUpdate - Create a DiscoveryRule
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - healthModelName - Name of health model resource
//   - discoveryRuleName - Name of the discovery rule. Must be unique within a health model.
//   - resource - Resource create parameters.
//   - options - DiscoveryRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the DiscoveryRulesClient.BeginCreateOrUpdate
//     method.
func (client *DiscoveryRulesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, resource DiscoveryRule, options *DiscoveryRulesClientBeginCreateOrUpdateOptions) (*runtime.Poller[DiscoveryRulesClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceGroupName, healthModelName, discoveryRuleName, resource, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiscoveryRulesClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiscoveryRulesClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Create a DiscoveryRule
// If the operation fails it returns an *azcore.ResponseError type.
func (client *DiscoveryRulesClient) createOrUpdate(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, resource DiscoveryRule, options *DiscoveryRulesClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "DiscoveryRulesClient.BeginCreateOrUpdate"
	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, resourceGroupName, healthModelName, discoveryRuleName, 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
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *DiscoveryRulesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, resource DiscoveryRule, _ *DiscoveryRulesClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName}"
	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 healthModelName == "" {
		return nil, errors.New("parameter healthModelName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName))
	if discoveryRuleName == "" {
		return nil, errors.New("parameter discoveryRuleName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{discoveryRuleName}", url.PathEscape(discoveryRuleName))
	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", version20260501Preview)
	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, resource); err != nil {
		return nil, err
	}
	return req, nil
}

// BeginDelete - Delete a DiscoveryRule
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - healthModelName - Name of health model resource
//   - discoveryRuleName - Name of the discovery rule. Must be unique within a health model.
//   - options - DiscoveryRulesClientBeginDeleteOptions contains the optional parameters for the DiscoveryRulesClient.BeginDelete
//     method.
func (client *DiscoveryRulesClient) BeginDelete(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, options *DiscoveryRulesClientBeginDeleteOptions) (*runtime.Poller[DiscoveryRulesClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, healthModelName, discoveryRuleName, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiscoveryRulesClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiscoveryRulesClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Delete a DiscoveryRule
// If the operation fails it returns an *azcore.ResponseError type.
func (client *DiscoveryRulesClient) deleteOperation(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, options *DiscoveryRulesClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "DiscoveryRulesClient.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, healthModelName, discoveryRuleName, 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, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// deleteCreateRequest creates the Delete request.
func (client *DiscoveryRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, _ *DiscoveryRulesClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName}"
	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 healthModelName == "" {
		return nil, errors.New("parameter healthModelName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName))
	if discoveryRuleName == "" {
		return nil, errors.New("parameter discoveryRuleName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{discoveryRuleName}", url.PathEscape(discoveryRuleName))
	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", version20260501Preview)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	return req, nil
}

// Get - Get a DiscoveryRule
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - healthModelName - Name of health model resource
//   - discoveryRuleName - Name of the discovery rule. Must be unique within a health model.
//   - options - DiscoveryRulesClientGetOptions contains the optional parameters for the DiscoveryRulesClient.Get method.
func (client *DiscoveryRulesClient) Get(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, options *DiscoveryRulesClientGetOptions) (DiscoveryRulesClientGetResponse, error) {
	var err error
	const operationName = "DiscoveryRulesClient.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, healthModelName, discoveryRuleName, options)
	if err != nil {
		return DiscoveryRulesClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return DiscoveryRulesClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return DiscoveryRulesClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *DiscoveryRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, _ *DiscoveryRulesClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName}"
	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 healthModelName == "" {
		return nil, errors.New("parameter healthModelName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName))
	if discoveryRuleName == "" {
		return nil, errors.New("parameter discoveryRuleName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{discoveryRuleName}", url.PathEscape(discoveryRuleName))
	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", version20260501Preview)
	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 *DiscoveryRulesClient) getHandleResponse(resp *http.Response) (DiscoveryRulesClientGetResponse, error) {
	result := DiscoveryRulesClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.DiscoveryRule); err != nil {
		return DiscoveryRulesClientGetResponse{}, err
	}
	return result, nil
}

// NewListByHealthModelPager - List DiscoveryRule resources by HealthModel
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - healthModelName - Name of health model resource
//   - options - DiscoveryRulesClientListByHealthModelOptions contains the optional parameters for the DiscoveryRulesClient.NewListByHealthModelPager
//     method.
func (client *DiscoveryRulesClient) NewListByHealthModelPager(resourceGroupName string, healthModelName string, options *DiscoveryRulesClientListByHealthModelOptions) *runtime.Pager[DiscoveryRulesClientListByHealthModelResponse] {
	return runtime.NewPager(runtime.PagingHandler[DiscoveryRulesClientListByHealthModelResponse]{
		More: func(page DiscoveryRulesClientListByHealthModelResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *DiscoveryRulesClientListByHealthModelResponse) (DiscoveryRulesClientListByHealthModelResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiscoveryRulesClient.NewListByHealthModelPager")
			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.listByHealthModelCreateRequest(ctx, resourceGroupName, healthModelName, options)
			}, nil)
			if err != nil {
				return DiscoveryRulesClientListByHealthModelResponse{}, err
			}
			return client.listByHealthModelHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByHealthModelCreateRequest creates the ListByHealthModel request.
func (client *DiscoveryRulesClient) listByHealthModelCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, options *DiscoveryRulesClientListByHealthModelOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules"
	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 healthModelName == "" {
		return nil, errors.New("parameter healthModelName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName))
	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", version20260501Preview)
	if options != nil && options.Timestamp != nil {
		reqQP.Set("timestamp", datetime.RFC3339(*options.Timestamp).String())
	}
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByHealthModelHandleResponse handles the ListByHealthModel response.
func (client *DiscoveryRulesClient) listByHealthModelHandleResponse(resp *http.Response) (DiscoveryRulesClientListByHealthModelResponse, error) {
	result := DiscoveryRulesClientListByHealthModelResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.DiscoveryRuleListResult); err != nil {
		return DiscoveryRulesClientListByHealthModelResponse{}, err
	}
	return result, nil
}
