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

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

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

// BeginCreateOrUpdate - Create a SignalDefinition
// 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
//   - signalDefinitionName - Name of the signal definition. Must be unique within a health model.
//   - resource - Resource create parameters.
//   - options - SignalDefinitionsClientBeginCreateOrUpdateOptions contains the optional parameters for the SignalDefinitionsClient.BeginCreateOrUpdate
//     method.
func (client *SignalDefinitionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, resource SignalDefinition, options *SignalDefinitionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[SignalDefinitionsClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceGroupName, healthModelName, signalDefinitionName, resource, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SignalDefinitionsClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SignalDefinitionsClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Create a SignalDefinition
// If the operation fails it returns an *azcore.ResponseError type.
func (client *SignalDefinitionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, resource SignalDefinition, options *SignalDefinitionsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "SignalDefinitionsClient.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, signalDefinitionName, 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 *SignalDefinitionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, resource SignalDefinition, _ *SignalDefinitionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName}"
	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 signalDefinitionName == "" {
		return nil, errors.New("parameter signalDefinitionName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{signalDefinitionName}", url.PathEscape(signalDefinitionName))
	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 SignalDefinition
// 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
//   - signalDefinitionName - Name of the signal definition. Must be unique within a health model.
//   - options - SignalDefinitionsClientBeginDeleteOptions contains the optional parameters for the SignalDefinitionsClient.BeginDelete
//     method.
func (client *SignalDefinitionsClient) BeginDelete(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, options *SignalDefinitionsClientBeginDeleteOptions) (*runtime.Poller[SignalDefinitionsClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, healthModelName, signalDefinitionName, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SignalDefinitionsClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SignalDefinitionsClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Delete a SignalDefinition
// If the operation fails it returns an *azcore.ResponseError type.
func (client *SignalDefinitionsClient) deleteOperation(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, options *SignalDefinitionsClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "SignalDefinitionsClient.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, signalDefinitionName, 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 *SignalDefinitionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, _ *SignalDefinitionsClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName}"
	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 signalDefinitionName == "" {
		return nil, errors.New("parameter signalDefinitionName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{signalDefinitionName}", url.PathEscape(signalDefinitionName))
	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 SignalDefinition
// 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
//   - signalDefinitionName - Name of the signal definition. Must be unique within a health model.
//   - options - SignalDefinitionsClientGetOptions contains the optional parameters for the SignalDefinitionsClient.Get method.
func (client *SignalDefinitionsClient) Get(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, options *SignalDefinitionsClientGetOptions) (SignalDefinitionsClientGetResponse, error) {
	var err error
	const operationName = "SignalDefinitionsClient.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, signalDefinitionName, options)
	if err != nil {
		return SignalDefinitionsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SignalDefinitionsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return SignalDefinitionsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

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

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

// listByHealthModelCreateRequest creates the ListByHealthModel request.
func (client *SignalDefinitionsClient) listByHealthModelCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, options *SignalDefinitionsClientListByHealthModelOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions"
	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 *SignalDefinitionsClient) listByHealthModelHandleResponse(resp *http.Response) (SignalDefinitionsClientListByHealthModelResponse, error) {
	result := SignalDefinitionsClientListByHealthModelResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.SignalDefinitionListResult); err != nil {
		return SignalDefinitionsClientListByHealthModelResponse{}, err
	}
	return result, nil
}
