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

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

// RecoveryPlansClient - Operations for managing Recovery Orchestration Plans.
// Don't use this type directly, use NewRecoveryPlansClient() instead.
//
// Generated from API version 2026-04-01-preview
type RecoveryPlansClient struct {
	internal *arm.Client
}

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

// BeginCreateOrUpdate - Create a RecoveryPlan
// If the operation fails it returns an *azcore.ResponseError type.
//   - serviceGroupName - The name of the service group.
//   - recoveryPlanName - The name of the recovery orchestration plan.
//   - resource - Resource create parameters.
//   - options - RecoveryPlansClientBeginCreateOrUpdateOptions contains the optional parameters for the RecoveryPlansClient.BeginCreateOrUpdate
//     method.
func (client *RecoveryPlansClient) BeginCreateOrUpdate(ctx context.Context, serviceGroupName string, recoveryPlanName string, resource RecoveryPlan, options *RecoveryPlansClientBeginCreateOrUpdateOptions) (*runtime.Poller[RecoveryPlansClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, serviceGroupName, recoveryPlanName, resource, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RecoveryPlansClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RecoveryPlansClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Create a RecoveryPlan
// If the operation fails it returns an *azcore.ResponseError type.
func (client *RecoveryPlansClient) createOrUpdate(ctx context.Context, serviceGroupName string, recoveryPlanName string, resource RecoveryPlan, options *RecoveryPlansClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "RecoveryPlansClient.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, serviceGroupName, recoveryPlanName, 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 *RecoveryPlansClient) createOrUpdateCreateRequest(ctx context.Context, serviceGroupName string, recoveryPlanName string, resource RecoveryPlan, _ *RecoveryPlansClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Management/serviceGroups/{serviceGroupName}/providers/Microsoft.AzureResilienceManagement/recoveryPlans/{recoveryPlanName}"
	if serviceGroupName == "" {
		return nil, errors.New("parameter serviceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceGroupName}", url.PathEscape(serviceGroupName))
	if recoveryPlanName == "" {
		return nil, errors.New("parameter recoveryPlanName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{recoveryPlanName}", url.PathEscape(recoveryPlanName))
	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", version20260401Preview)
	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 RecoveryPlan
// If the operation fails it returns an *azcore.ResponseError type.
//   - serviceGroupName - The name of the service group.
//   - recoveryPlanName - The name of the recovery orchestration plan.
//   - options - RecoveryPlansClientBeginDeleteOptions contains the optional parameters for the RecoveryPlansClient.BeginDelete
//     method.
func (client *RecoveryPlansClient) BeginDelete(ctx context.Context, serviceGroupName string, recoveryPlanName string, options *RecoveryPlansClientBeginDeleteOptions) (*runtime.Poller[RecoveryPlansClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, serviceGroupName, recoveryPlanName, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RecoveryPlansClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RecoveryPlansClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Delete a RecoveryPlan
// If the operation fails it returns an *azcore.ResponseError type.
func (client *RecoveryPlansClient) deleteOperation(ctx context.Context, serviceGroupName string, recoveryPlanName string, options *RecoveryPlansClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "RecoveryPlansClient.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, serviceGroupName, recoveryPlanName, 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 *RecoveryPlansClient) deleteCreateRequest(ctx context.Context, serviceGroupName string, recoveryPlanName string, _ *RecoveryPlansClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Management/serviceGroups/{serviceGroupName}/providers/Microsoft.AzureResilienceManagement/recoveryPlans/{recoveryPlanName}"
	if serviceGroupName == "" {
		return nil, errors.New("parameter serviceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceGroupName}", url.PathEscape(serviceGroupName))
	if recoveryPlanName == "" {
		return nil, errors.New("parameter recoveryPlanName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{recoveryPlanName}", url.PathEscape(recoveryPlanName))
	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", version20260401Preview)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	return req, nil
}

// Get - Get a RecoveryPlan
// If the operation fails it returns an *azcore.ResponseError type.
//   - serviceGroupName - The name of the service group.
//   - recoveryPlanName - The name of the recovery orchestration plan.
//   - options - RecoveryPlansClientGetOptions contains the optional parameters for the RecoveryPlansClient.Get method.
func (client *RecoveryPlansClient) Get(ctx context.Context, serviceGroupName string, recoveryPlanName string, options *RecoveryPlansClientGetOptions) (RecoveryPlansClientGetResponse, error) {
	var err error
	const operationName = "RecoveryPlansClient.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, serviceGroupName, recoveryPlanName, options)
	if err != nil {
		return RecoveryPlansClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return RecoveryPlansClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return RecoveryPlansClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *RecoveryPlansClient) getCreateRequest(ctx context.Context, serviceGroupName string, recoveryPlanName string, _ *RecoveryPlansClientGetOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Management/serviceGroups/{serviceGroupName}/providers/Microsoft.AzureResilienceManagement/recoveryPlans/{recoveryPlanName}"
	if serviceGroupName == "" {
		return nil, errors.New("parameter serviceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceGroupName}", url.PathEscape(serviceGroupName))
	if recoveryPlanName == "" {
		return nil, errors.New("parameter recoveryPlanName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{recoveryPlanName}", url.PathEscape(recoveryPlanName))
	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", version20260401Preview)
	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 *RecoveryPlansClient) getHandleResponse(resp *http.Response) (RecoveryPlansClientGetResponse, error) {
	result := RecoveryPlansClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.RecoveryPlan); err != nil {
		return RecoveryPlansClientGetResponse{}, err
	}
	return result, nil
}

// NewListPager - List RecoveryPlan resources by tenant
//   - serviceGroupName - The name of the service group.
//   - options - RecoveryPlansClientListOptions contains the optional parameters for the RecoveryPlansClient.NewListPager method.
func (client *RecoveryPlansClient) NewListPager(serviceGroupName string, options *RecoveryPlansClientListOptions) *runtime.Pager[RecoveryPlansClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[RecoveryPlansClientListResponse]{
		More: func(page RecoveryPlansClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *RecoveryPlansClientListResponse) (RecoveryPlansClientListResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RecoveryPlansClient.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, serviceGroupName, options)
			}, nil)
			if err != nil {
				return RecoveryPlansClientListResponse{}, err
			}
			return client.listHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listCreateRequest creates the List request.
func (client *RecoveryPlansClient) listCreateRequest(ctx context.Context, serviceGroupName string, options *RecoveryPlansClientListOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Management/serviceGroups/{serviceGroupName}/providers/Microsoft.AzureResilienceManagement/recoveryPlans"
	if serviceGroupName == "" {
		return nil, errors.New("parameter serviceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceGroupName}", url.PathEscape(serviceGroupName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	if options != nil && options.SkipToken != nil {
		reqQP.Set("$skipToken", *options.SkipToken)
	}
	if options != nil && options.Top != nil {
		reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10))
	}
	reqQP.Set("api-version", version20260401Preview)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// BeginUpdate - Update a RecoveryPlan
// If the operation fails it returns an *azcore.ResponseError type.
//   - serviceGroupName - The name of the service group.
//   - recoveryPlanName - The name of the recovery orchestration plan.
//   - properties - The resource properties to be updated.
//   - options - RecoveryPlansClientBeginUpdateOptions contains the optional parameters for the RecoveryPlansClient.BeginUpdate
//     method.
func (client *RecoveryPlansClient) BeginUpdate(ctx context.Context, serviceGroupName string, recoveryPlanName string, properties RecoveryPlan, options *RecoveryPlansClientBeginUpdateOptions) (*runtime.Poller[RecoveryPlansClientUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.update(ctx, serviceGroupName, recoveryPlanName, properties, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RecoveryPlansClientUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RecoveryPlansClientUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Update - Update a RecoveryPlan
// If the operation fails it returns an *azcore.ResponseError type.
func (client *RecoveryPlansClient) update(ctx context.Context, serviceGroupName string, recoveryPlanName string, properties RecoveryPlan, options *RecoveryPlansClientBeginUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "RecoveryPlansClient.BeginUpdate"
	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, serviceGroupName, recoveryPlanName, properties, 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) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// updateCreateRequest creates the Update request.
func (client *RecoveryPlansClient) updateCreateRequest(ctx context.Context, serviceGroupName string, recoveryPlanName string, properties RecoveryPlan, _ *RecoveryPlansClientBeginUpdateOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Management/serviceGroups/{serviceGroupName}/providers/Microsoft.AzureResilienceManagement/recoveryPlans/{recoveryPlanName}"
	if serviceGroupName == "" {
		return nil, errors.New("parameter serviceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceGroupName}", url.PathEscape(serviceGroupName))
	if recoveryPlanName == "" {
		return nil, errors.New("parameter recoveryPlanName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{recoveryPlanName}", url.PathEscape(recoveryPlanName))
	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", version20260401Preview)
	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, properties); err != nil {
		return nil, err
	}
	return req, nil
}
