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

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

// PlansClient contains the methods for the Plans group.
// Don't use this type directly, use NewPlansClient() instead.
//
// Generated from API version 2026-07-03-preview
type PlansClient struct {
	internal       *arm.Client
	subscriptionID string
}

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

// BeginCreateOrupdate - Create a CommvaultPlan
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - cloudAccountName - Name of the Cloud Account resource
//   - planName - Name of the Plan resource
//   - resource - Resource create parameters.
//   - options - PlansClientBeginCreateOrupdateOptions contains the optional parameters for the PlansClient.BeginCreateOrupdate
//     method.
func (client *PlansClient) BeginCreateOrupdate(ctx context.Context, resourceGroupName string, cloudAccountName string, planName string, resource CommvaultPlan, options *PlansClientBeginCreateOrupdateOptions) (*runtime.Poller[PlansClientCreateOrupdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrupdate(ctx, resourceGroupName, cloudAccountName, planName, resource, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PlansClientCreateOrupdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PlansClientCreateOrupdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrupdate - Create a CommvaultPlan
// If the operation fails it returns an *azcore.ResponseError type.
func (client *PlansClient) createOrupdate(ctx context.Context, resourceGroupName string, cloudAccountName string, planName string, resource CommvaultPlan, options *PlansClientBeginCreateOrupdateOptions) (*http.Response, error) {
	var err error
	const operationName = "PlansClient.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, cloudAccountName, planName, 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 *PlansClient) createOrupdateCreateRequest(ctx context.Context, resourceGroupName string, cloudAccountName string, planName string, resource CommvaultPlan, _ *PlansClientBeginCreateOrupdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Commvault.ContentStore/cloudAccounts/{cloudAccountName}/plans/{planName}"
	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 cloudAccountName == "" {
		return nil, errors.New("parameter cloudAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{cloudAccountName}", url.PathEscape(cloudAccountName))
	if planName == "" {
		return nil, errors.New("parameter planName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{planName}", url.PathEscape(planName))
	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", version20260703Preview)
	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 CommvaultPlan
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - cloudAccountName - Name of the Cloud Account resource
//   - planName - Name of the Plan resource
//   - options - PlansClientBeginDeleteOptions contains the optional parameters for the PlansClient.BeginDelete method.
func (client *PlansClient) BeginDelete(ctx context.Context, resourceGroupName string, cloudAccountName string, planName string, options *PlansClientBeginDeleteOptions) (*runtime.Poller[PlansClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, cloudAccountName, planName, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PlansClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PlansClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Delete a CommvaultPlan
// If the operation fails it returns an *azcore.ResponseError type.
func (client *PlansClient) deleteOperation(ctx context.Context, resourceGroupName string, cloudAccountName string, planName string, options *PlansClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "PlansClient.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, cloudAccountName, planName, 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 *PlansClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, cloudAccountName string, planName string, _ *PlansClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Commvault.ContentStore/cloudAccounts/{cloudAccountName}/plans/{planName}"
	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 cloudAccountName == "" {
		return nil, errors.New("parameter cloudAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{cloudAccountName}", url.PathEscape(cloudAccountName))
	if planName == "" {
		return nil, errors.New("parameter planName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{planName}", url.PathEscape(planName))
	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", version20260703Preview)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	return req, nil
}

// Get - Get a CommvaultPlan
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - cloudAccountName - Name of the Cloud Account resource
//   - planName - Name of the Plan resource
//   - options - PlansClientGetOptions contains the optional parameters for the PlansClient.Get method.
func (client *PlansClient) Get(ctx context.Context, resourceGroupName string, cloudAccountName string, planName string, options *PlansClientGetOptions) (PlansClientGetResponse, error) {
	var err error
	const operationName = "PlansClient.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, cloudAccountName, planName, options)
	if err != nil {
		return PlansClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return PlansClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return PlansClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *PlansClient) getCreateRequest(ctx context.Context, resourceGroupName string, cloudAccountName string, planName string, _ *PlansClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Commvault.ContentStore/cloudAccounts/{cloudAccountName}/plans/{planName}"
	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 cloudAccountName == "" {
		return nil, errors.New("parameter cloudAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{cloudAccountName}", url.PathEscape(cloudAccountName))
	if planName == "" {
		return nil, errors.New("parameter planName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{planName}", url.PathEscape(planName))
	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", version20260703Preview)
	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 *PlansClient) getHandleResponse(resp *http.Response) (PlansClientGetResponse, error) {
	result := PlansClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CommvaultPlan); err != nil {
		return PlansClientGetResponse{}, err
	}
	return result, nil
}

// NewListByCloudAccountPager - List CommvaultPlan resources by CloudAccount
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - cloudAccountName - Name of the Cloud Account resource
//   - options - PlansClientListByCloudAccountOptions contains the optional parameters for the PlansClient.NewListByCloudAccountPager
//     method.
func (client *PlansClient) NewListByCloudAccountPager(resourceGroupName string, cloudAccountName string, options *PlansClientListByCloudAccountOptions) *runtime.Pager[PlansClientListByCloudAccountResponse] {
	return runtime.NewPager(runtime.PagingHandler[PlansClientListByCloudAccountResponse]{
		More: func(page PlansClientListByCloudAccountResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *PlansClientListByCloudAccountResponse) (PlansClientListByCloudAccountResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PlansClient.NewListByCloudAccountPager")
			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.listByCloudAccountCreateRequest(ctx, resourceGroupName, cloudAccountName, options)
			}, nil)
			if err != nil {
				return PlansClientListByCloudAccountResponse{}, err
			}
			return client.listByCloudAccountHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByCloudAccountCreateRequest creates the ListByCloudAccount request.
func (client *PlansClient) listByCloudAccountCreateRequest(ctx context.Context, resourceGroupName string, cloudAccountName string, _ *PlansClientListByCloudAccountOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Commvault.ContentStore/cloudAccounts/{cloudAccountName}/plans"
	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 cloudAccountName == "" {
		return nil, errors.New("parameter cloudAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{cloudAccountName}", url.PathEscape(cloudAccountName))
	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", version20260703Preview)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByCloudAccountHandleResponse handles the ListByCloudAccount response.
func (client *PlansClient) listByCloudAccountHandleResponse(resp *http.Response) (PlansClientListByCloudAccountResponse, error) {
	result := PlansClientListByCloudAccountResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CommvaultPlanListResult); err != nil {
		return PlansClientListByCloudAccountResponse{}, err
	}
	return result, nil
}
