//go:build go1.18
// +build go1.18

// 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) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

package armbilling

import (
	"context"
	"errors"
	"net/http"
	"net/url"
	"strconv"
	"strings"

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

// AssociatedTenantsClient contains the methods for the AssociatedTenants group.
// Don't use this type directly, use NewAssociatedTenantsClient() instead.
type AssociatedTenantsClient struct {
	internal *arm.Client
}

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

// BeginCreateOrUpdate - Create or update an associated tenant for the billing account.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
//   - billingAccountName - The ID that uniquely identifies a billing account.
//   - associatedTenantName - The ID that uniquely identifies a tenant.
//   - parameters - An associated tenant.
//   - options - AssociatedTenantsClientBeginCreateOrUpdateOptions contains the optional parameters for the AssociatedTenantsClient.BeginCreateOrUpdate
//     method.
func (client *AssociatedTenantsClient) BeginCreateOrUpdate(ctx context.Context, billingAccountName string, associatedTenantName string, parameters AssociatedTenant, options *AssociatedTenantsClientBeginCreateOrUpdateOptions) (*runtime.Poller[AssociatedTenantsClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, billingAccountName, associatedTenantName, parameters, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AssociatedTenantsClientCreateOrUpdateResponse]{
			FinalStateVia: runtime.FinalStateViaLocation,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AssociatedTenantsClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Create or update an associated tenant for the billing account.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
func (client *AssociatedTenantsClient) createOrUpdate(ctx context.Context, billingAccountName string, associatedTenantName string, parameters AssociatedTenant, options *AssociatedTenantsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "AssociatedTenantsClient.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, associatedTenantName, 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) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *AssociatedTenantsClient) createOrUpdateCreateRequest(ctx context.Context, billingAccountName string, associatedTenantName string, parameters AssociatedTenant, options *AssociatedTenantsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/associatedTenants/{associatedTenantName}"
	if billingAccountName == "" {
		return nil, errors.New("parameter billingAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{billingAccountName}", url.PathEscape(billingAccountName))
	if associatedTenantName == "" {
		return nil, errors.New("parameter associatedTenantName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{associatedTenantName}", url.PathEscape(associatedTenantName))
	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", "2024-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, parameters); err != nil {
		return nil, err
	}
	return req, nil
}

// BeginDelete - Deletes an associated tenant for a billing account.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
//   - billingAccountName - The ID that uniquely identifies a billing account.
//   - associatedTenantName - The ID that uniquely identifies a tenant.
//   - options - AssociatedTenantsClientBeginDeleteOptions contains the optional parameters for the AssociatedTenantsClient.BeginDelete
//     method.
func (client *AssociatedTenantsClient) BeginDelete(ctx context.Context, billingAccountName string, associatedTenantName string, options *AssociatedTenantsClientBeginDeleteOptions) (*runtime.Poller[AssociatedTenantsClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, billingAccountName, associatedTenantName, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AssociatedTenantsClientDeleteResponse]{
			FinalStateVia: runtime.FinalStateViaLocation,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AssociatedTenantsClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Deletes an associated tenant for a billing account.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
func (client *AssociatedTenantsClient) deleteOperation(ctx context.Context, billingAccountName string, associatedTenantName string, options *AssociatedTenantsClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "AssociatedTenantsClient.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, billingAccountName, associatedTenantName, 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 *AssociatedTenantsClient) deleteCreateRequest(ctx context.Context, billingAccountName string, associatedTenantName string, options *AssociatedTenantsClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/associatedTenants/{associatedTenantName}"
	if billingAccountName == "" {
		return nil, errors.New("parameter billingAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{billingAccountName}", url.PathEscape(billingAccountName))
	if associatedTenantName == "" {
		return nil, errors.New("parameter associatedTenantName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{associatedTenantName}", url.PathEscape(associatedTenantName))
	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", "2024-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Gets an associated tenant by ID.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
//   - billingAccountName - The ID that uniquely identifies a billing account.
//   - associatedTenantName - The ID that uniquely identifies a tenant.
//   - options - AssociatedTenantsClientGetOptions contains the optional parameters for the AssociatedTenantsClient.Get method.
func (client *AssociatedTenantsClient) Get(ctx context.Context, billingAccountName string, associatedTenantName string, options *AssociatedTenantsClientGetOptions) (AssociatedTenantsClientGetResponse, error) {
	var err error
	const operationName = "AssociatedTenantsClient.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, associatedTenantName, options)
	if err != nil {
		return AssociatedTenantsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return AssociatedTenantsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return AssociatedTenantsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *AssociatedTenantsClient) getCreateRequest(ctx context.Context, billingAccountName string, associatedTenantName string, options *AssociatedTenantsClientGetOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/associatedTenants/{associatedTenantName}"
	if billingAccountName == "" {
		return nil, errors.New("parameter billingAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{billingAccountName}", url.PathEscape(billingAccountName))
	if associatedTenantName == "" {
		return nil, errors.New("parameter associatedTenantName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{associatedTenantName}", url.PathEscape(associatedTenantName))
	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", "2024-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *AssociatedTenantsClient) getHandleResponse(resp *http.Response) (AssociatedTenantsClientGetResponse, error) {
	result := AssociatedTenantsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.AssociatedTenant); err != nil {
		return AssociatedTenantsClientGetResponse{}, err
	}
	return result, nil
}

// NewListByBillingAccountPager - Lists the associated tenants that can collaborate with the billing account on commerce activities
// like viewing and downloading invoices, managing payments, making purchases, and managing or
// provisioning licenses.
//
// Generated from API version 2024-04-01
//   - billingAccountName - The ID that uniquely identifies a billing account.
//   - options - AssociatedTenantsClientListByBillingAccountOptions contains the optional parameters for the AssociatedTenantsClient.NewListByBillingAccountPager
//     method.
func (client *AssociatedTenantsClient) NewListByBillingAccountPager(billingAccountName string, options *AssociatedTenantsClientListByBillingAccountOptions) *runtime.Pager[AssociatedTenantsClientListByBillingAccountResponse] {
	return runtime.NewPager(runtime.PagingHandler[AssociatedTenantsClientListByBillingAccountResponse]{
		More: func(page AssociatedTenantsClientListByBillingAccountResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *AssociatedTenantsClientListByBillingAccountResponse) (AssociatedTenantsClientListByBillingAccountResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AssociatedTenantsClient.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 AssociatedTenantsClientListByBillingAccountResponse{}, err
			}
			return client.listByBillingAccountHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByBillingAccountCreateRequest creates the ListByBillingAccount request.
func (client *AssociatedTenantsClient) listByBillingAccountCreateRequest(ctx context.Context, billingAccountName string, options *AssociatedTenantsClientListByBillingAccountOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/associatedTenants"
	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", "2024-04-01")
	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.IncludeRevoked != nil {
		reqQP.Set("includeRevoked", strconv.FormatBool(*options.IncludeRevoked))
	}
	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 = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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