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

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

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

// Get - Gets a customer by its ID. The operation is supported only for billing accounts with agreement type Microsoft Partner
// Agreement.
// 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.
//   - billingProfileName - The ID that uniquely identifies a billing profile.
//   - customerName - The ID that uniquely identifies a customer.
//   - options - CustomersClientGetOptions contains the optional parameters for the CustomersClient.Get method.
func (client *CustomersClient) Get(ctx context.Context, billingAccountName string, billingProfileName string, customerName string, options *CustomersClientGetOptions) (CustomersClientGetResponse, error) {
	var err error
	const operationName = "CustomersClient.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, billingProfileName, customerName, options)
	if err != nil {
		return CustomersClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return CustomersClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return CustomersClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *CustomersClient) getCreateRequest(ctx context.Context, billingAccountName string, billingProfileName string, customerName string, options *CustomersClientGetOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers/{customerName}"
	if billingAccountName == "" {
		return nil, errors.New("parameter billingAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{billingAccountName}", url.PathEscape(billingAccountName))
	if billingProfileName == "" {
		return nil, errors.New("parameter billingProfileName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{billingProfileName}", url.PathEscape(billingProfileName))
	if customerName == "" {
		return nil, errors.New("parameter customerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{customerName}", url.PathEscape(customerName))
	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 *CustomersClient) getHandleResponse(resp *http.Response) (CustomersClientGetResponse, error) {
	result := CustomersClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Customer); err != nil {
		return CustomersClientGetResponse{}, err
	}
	return result, nil
}

// GetByBillingAccount - Gets a customer by its ID at billing account level. The operation is supported only for billing accounts
// with agreement type Microsoft Partner Agreement.
// 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.
//   - customerName - The ID that uniquely identifies a customer.
//   - options - CustomersClientGetByBillingAccountOptions contains the optional parameters for the CustomersClient.GetByBillingAccount
//     method.
func (client *CustomersClient) GetByBillingAccount(ctx context.Context, billingAccountName string, customerName string, options *CustomersClientGetByBillingAccountOptions) (CustomersClientGetByBillingAccountResponse, error) {
	var err error
	const operationName = "CustomersClient.GetByBillingAccount"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.getByBillingAccountCreateRequest(ctx, billingAccountName, customerName, options)
	if err != nil {
		return CustomersClientGetByBillingAccountResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return CustomersClientGetByBillingAccountResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return CustomersClientGetByBillingAccountResponse{}, err
	}
	resp, err := client.getByBillingAccountHandleResponse(httpResp)
	return resp, err
}

// getByBillingAccountCreateRequest creates the GetByBillingAccount request.
func (client *CustomersClient) getByBillingAccountCreateRequest(ctx context.Context, billingAccountName string, customerName string, options *CustomersClientGetByBillingAccountOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}"
	if billingAccountName == "" {
		return nil, errors.New("parameter billingAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{billingAccountName}", url.PathEscape(billingAccountName))
	if customerName == "" {
		return nil, errors.New("parameter customerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{customerName}", url.PathEscape(customerName))
	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
}

// getByBillingAccountHandleResponse handles the GetByBillingAccount response.
func (client *CustomersClient) getByBillingAccountHandleResponse(resp *http.Response) (CustomersClientGetByBillingAccountResponse, error) {
	result := CustomersClientGetByBillingAccountResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Customer); err != nil {
		return CustomersClientGetByBillingAccountResponse{}, err
	}
	return result, nil
}

// NewListByBillingAccountPager - Lists the customers that are billed to a billing account. The operation is supported only
// for billing accounts with agreement type Microsoft Partner Agreement.
//
// Generated from API version 2024-04-01
//   - billingAccountName - The ID that uniquely identifies a billing account.
//   - options - CustomersClientListByBillingAccountOptions contains the optional parameters for the CustomersClient.NewListByBillingAccountPager
//     method.
func (client *CustomersClient) NewListByBillingAccountPager(billingAccountName string, options *CustomersClientListByBillingAccountOptions) *runtime.Pager[CustomersClientListByBillingAccountResponse] {
	return runtime.NewPager(runtime.PagingHandler[CustomersClientListByBillingAccountResponse]{
		More: func(page CustomersClientListByBillingAccountResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *CustomersClientListByBillingAccountResponse) (CustomersClientListByBillingAccountResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CustomersClient.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 CustomersClientListByBillingAccountResponse{}, err
			}
			return client.listByBillingAccountHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByBillingAccountCreateRequest creates the ListByBillingAccount request.
func (client *CustomersClient) listByBillingAccountCreateRequest(ctx context.Context, billingAccountName string, options *CustomersClientListByBillingAccountOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers"
	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.Expand != nil {
		reqQP.Set("expand", *options.Expand)
	}
	if options != nil && options.Filter != nil {
		reqQP.Set("filter", *options.Filter)
	}
	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 *CustomersClient) listByBillingAccountHandleResponse(resp *http.Response) (CustomersClientListByBillingAccountResponse, error) {
	result := CustomersClientListByBillingAccountResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CustomerListResult); err != nil {
		return CustomersClientListByBillingAccountResponse{}, err
	}
	return result, nil
}

// NewListByBillingProfilePager - Lists the customers that are billed to a billing profile. The operation is supported only
// for billing accounts with agreement type Microsoft Partner Agreement.
//
// Generated from API version 2024-04-01
//   - billingAccountName - The ID that uniquely identifies a billing account.
//   - billingProfileName - The ID that uniquely identifies a billing profile.
//   - options - CustomersClientListByBillingProfileOptions contains the optional parameters for the CustomersClient.NewListByBillingProfilePager
//     method.
func (client *CustomersClient) NewListByBillingProfilePager(billingAccountName string, billingProfileName string, options *CustomersClientListByBillingProfileOptions) *runtime.Pager[CustomersClientListByBillingProfileResponse] {
	return runtime.NewPager(runtime.PagingHandler[CustomersClientListByBillingProfileResponse]{
		More: func(page CustomersClientListByBillingProfileResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *CustomersClientListByBillingProfileResponse) (CustomersClientListByBillingProfileResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CustomersClient.NewListByBillingProfilePager")
			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.listByBillingProfileCreateRequest(ctx, billingAccountName, billingProfileName, options)
			}, nil)
			if err != nil {
				return CustomersClientListByBillingProfileResponse{}, err
			}
			return client.listByBillingProfileHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByBillingProfileCreateRequest creates the ListByBillingProfile request.
func (client *CustomersClient) listByBillingProfileCreateRequest(ctx context.Context, billingAccountName string, billingProfileName string, options *CustomersClientListByBillingProfileOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers"
	if billingAccountName == "" {
		return nil, errors.New("parameter billingAccountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{billingAccountName}", url.PathEscape(billingAccountName))
	if billingProfileName == "" {
		return nil, errors.New("parameter billingProfileName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{billingProfileName}", url.PathEscape(billingProfileName))
	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.Expand != nil {
		reqQP.Set("expand", *options.Expand)
	}
	if options != nil && options.Filter != nil {
		reqQP.Set("filter", *options.Filter)
	}
	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
}

// listByBillingProfileHandleResponse handles the ListByBillingProfile response.
func (client *CustomersClient) listByBillingProfileHandleResponse(resp *http.Response) (CustomersClientListByBillingProfileResponse, error) {
	result := CustomersClientListByBillingProfileResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CustomerListResult); err != nil {
		return CustomersClientListByBillingProfileResponse{}, err
	}
	return result, nil
}
