// 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"
	"net/http"
	"net/url"
	"strings"
	"time"
)

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

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

// CreateOrUpdate - Create a Relationship
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-05-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - healthModelName - Name of health model resource
//   - relationshipName - Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName
//     and childEntityName can be used as the name.
//   - resource - Resource create parameters.
//   - options - RelationshipsClientCreateOrUpdateOptions contains the optional parameters for the RelationshipsClient.CreateOrUpdate
//     method.
func (client *RelationshipsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, resource Relationship, options *RelationshipsClientCreateOrUpdateOptions) (RelationshipsClientCreateOrUpdateResponse, error) {
	var err error
	const operationName = "RelationshipsClient.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, resourceGroupName, healthModelName, relationshipName, resource, options)
	if err != nil {
		return RelationshipsClientCreateOrUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return RelationshipsClientCreateOrUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return RelationshipsClientCreateOrUpdateResponse{}, err
	}
	resp, err := client.createOrUpdateHandleResponse(httpResp)
	return resp, err
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *RelationshipsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, resource Relationship, _ *RelationshipsClientCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName}"
	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 relationshipName == "" {
		return nil, errors.New("parameter relationshipName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{relationshipName}", url.PathEscape(relationshipName))
	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", "2025-05-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	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
}

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

// Delete - Delete a Relationship
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-05-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - healthModelName - Name of health model resource
//   - relationshipName - Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName
//     and childEntityName can be used as the name.
//   - options - RelationshipsClientDeleteOptions contains the optional parameters for the RelationshipsClient.Delete method.
func (client *RelationshipsClient) Delete(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, options *RelationshipsClientDeleteOptions) (RelationshipsClientDeleteResponse, error) {
	var err error
	const operationName = "RelationshipsClient.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, healthModelName, relationshipName, options)
	if err != nil {
		return RelationshipsClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return RelationshipsClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return RelationshipsClientDeleteResponse{}, err
	}
	return RelationshipsClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *RelationshipsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, _ *RelationshipsClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName}"
	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 relationshipName == "" {
		return nil, errors.New("parameter relationshipName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{relationshipName}", url.PathEscape(relationshipName))
	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", "2025-05-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	return req, nil
}

// Get - Get a Relationship
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-05-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - healthModelName - Name of health model resource
//   - relationshipName - Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName
//     and childEntityName can be used as the name.
//   - options - RelationshipsClientGetOptions contains the optional parameters for the RelationshipsClient.Get method.
func (client *RelationshipsClient) Get(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, options *RelationshipsClientGetOptions) (RelationshipsClientGetResponse, error) {
	var err error
	const operationName = "RelationshipsClient.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, relationshipName, options)
	if err != nil {
		return RelationshipsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return RelationshipsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return RelationshipsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

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

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

// listByHealthModelCreateRequest creates the ListByHealthModel request.
func (client *RelationshipsClient) listByHealthModelCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, options *RelationshipsClientListByHealthModelOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships"
	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", "2025-05-01-preview")
	if options != nil && options.Timestamp != nil {
		reqQP.Set("timestamp", options.Timestamp.Format(time.RFC3339Nano))
	}
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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