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

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

// SubscriptionsAliasesClient contains the methods for the SubscriptionsAliases group.
// Don't use this type directly, use NewSubscriptionsAliasesClient() instead.
//
// Generated from API version 2024-04-01
type SubscriptionsAliasesClient struct {
	internal *arm.Client
}

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

// BeginCreateOrUpdate - Creates or updates a billing subscription by its alias ID. The operation is supported for seat based
// billing subscriptions.
// If the operation fails it returns an *azcore.ResponseError type.
//   - billingAccountName - The ID that uniquely identifies a billing account.
//   - aliasName - The ID that uniquely identifies a subscription alias.
//   - parameters - A billing subscription alias.
//   - options - SubscriptionsAliasesClientBeginCreateOrUpdateOptions contains the optional parameters for the SubscriptionsAliasesClient.BeginCreateOrUpdate
//     method.
func (client *SubscriptionsAliasesClient) BeginCreateOrUpdate(ctx context.Context, billingAccountName string, aliasName string, parameters SubscriptionAlias, options *SubscriptionsAliasesClientBeginCreateOrUpdateOptions) (*runtime.Poller[SubscriptionsAliasesClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, billingAccountName, aliasName, parameters, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SubscriptionsAliasesClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SubscriptionsAliasesClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Creates or updates a billing subscription by its alias ID. The operation is supported for seat based billing
// subscriptions.
// If the operation fails it returns an *azcore.ResponseError type.
func (client *SubscriptionsAliasesClient) createOrUpdate(ctx context.Context, billingAccountName string, aliasName string, parameters SubscriptionAlias, options *SubscriptionsAliasesClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "SubscriptionsAliasesClient.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, billingAccountName, aliasName, parameters, 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, http.StatusAccepted) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *SubscriptionsAliasesClient) createOrUpdateCreateRequest(ctx context.Context, billingAccountName string, aliasName string, parameters SubscriptionAlias, _ *SubscriptionsAliasesClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptionAliases/{aliasName}"
	if billingAccountName == "" {
		return nil, errors.New("parameter billingAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{billingAccountName}", url.PathEscape(billingAccountName))
	if aliasName == "" {
		return nil, errors.New("parameter aliasName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{aliasName}", url.PathEscape(aliasName))
	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", version20240401)
	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, parameters); err != nil {
		return nil, err
	}
	return req, nil
}

// Get - Gets a subscription by its alias ID. The operation is supported for seat based billing subscriptions.
// If the operation fails it returns an *azcore.ResponseError type.
//   - billingAccountName - The ID that uniquely identifies a billing account.
//   - aliasName - The ID that uniquely identifies a subscription alias.
//   - options - SubscriptionsAliasesClientGetOptions contains the optional parameters for the SubscriptionsAliasesClient.Get
//     method.
func (client *SubscriptionsAliasesClient) Get(ctx context.Context, billingAccountName string, aliasName string, options *SubscriptionsAliasesClientGetOptions) (SubscriptionsAliasesClientGetResponse, error) {
	var err error
	const operationName = "SubscriptionsAliasesClient.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, billingAccountName, aliasName, options)
	if err != nil {
		return SubscriptionsAliasesClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SubscriptionsAliasesClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return SubscriptionsAliasesClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *SubscriptionsAliasesClient) getCreateRequest(ctx context.Context, billingAccountName string, aliasName string, _ *SubscriptionsAliasesClientGetOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptionAliases/{aliasName}"
	if billingAccountName == "" {
		return nil, errors.New("parameter billingAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{billingAccountName}", url.PathEscape(billingAccountName))
	if aliasName == "" {
		return nil, errors.New("parameter aliasName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{aliasName}", url.PathEscape(aliasName))
	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", version20240401)
	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 *SubscriptionsAliasesClient) getHandleResponse(resp *http.Response) (SubscriptionsAliasesClientGetResponse, error) {
	result := SubscriptionsAliasesClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.SubscriptionAlias); err != nil {
		return SubscriptionsAliasesClientGetResponse{}, err
	}
	return result, nil
}

// NewListByBillingAccountPager - Lists the subscription aliases for a billing account. The operation is supported for seat
// based billing subscriptions.
//   - billingAccountName - The ID that uniquely identifies a billing account.
//   - options - SubscriptionsAliasesClientListByBillingAccountOptions contains the optional parameters for the SubscriptionsAliasesClient.NewListByBillingAccountPager
//     method.
func (client *SubscriptionsAliasesClient) NewListByBillingAccountPager(billingAccountName string, options *SubscriptionsAliasesClientListByBillingAccountOptions) *runtime.Pager[SubscriptionsAliasesClientListByBillingAccountResponse] {
	return runtime.NewPager(runtime.PagingHandler[SubscriptionsAliasesClientListByBillingAccountResponse]{
		More: func(page SubscriptionsAliasesClientListByBillingAccountResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *SubscriptionsAliasesClientListByBillingAccountResponse) (SubscriptionsAliasesClientListByBillingAccountResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SubscriptionsAliasesClient.NewListByBillingAccountPager")
			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.listByBillingAccountCreateRequest(ctx, billingAccountName, options)
			}, nil)
			if err != nil {
				return SubscriptionsAliasesClientListByBillingAccountResponse{}, err
			}
			return client.listByBillingAccountHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByBillingAccountCreateRequest creates the ListByBillingAccount request.
func (client *SubscriptionsAliasesClient) listByBillingAccountCreateRequest(ctx context.Context, billingAccountName string, options *SubscriptionsAliasesClientListByBillingAccountOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptionAliases"
	if billingAccountName == "" {
		return nil, errors.New("parameter billingAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{billingAccountName}", url.PathEscape(billingAccountName))
	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", version20240401)
	if options != nil && options.Count != nil {
		reqQP.Set("count", strconv.FormatBool(*options.Count))
	}
	if options != nil && options.Filter != nil {
		reqQP.Set("filter", *options.Filter)
	}
	if options != nil && options.IncludeDeleted != nil {
		reqQP.Set("includeDeleted", strconv.FormatBool(*options.IncludeDeleted))
	}
	if options != nil && options.OrderBy != nil {
		reqQP.Set("orderBy", *options.OrderBy)
	}
	if options != nil && options.Search != nil {
		reqQP.Set("search", *options.Search)
	}
	if options != nil && options.Skip != nil {
		reqQP.Set("skip", strconv.FormatInt(*options.Skip, 10))
	}
	if options != nil && options.Top != nil {
		reqQP.Set("top", strconv.FormatInt(*options.Top, 10))
	}
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByBillingAccountHandleResponse handles the ListByBillingAccount response.
func (client *SubscriptionsAliasesClient) listByBillingAccountHandleResponse(resp *http.Response) (SubscriptionsAliasesClientListByBillingAccountResponse, error) {
	result := SubscriptionsAliasesClientListByBillingAccountResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.SubscriptionAliasListResult); err != nil {
		return SubscriptionsAliasesClientListByBillingAccountResponse{}, err
	}
	return result, nil
}
