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

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

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

// Get - Gets a department by ID. The operation is supported only for billing accounts with agreement type Enterprise Agreement.
// If the operation fails it returns an *azcore.ResponseError type.
//   - billingAccountName - The ID that uniquely identifies a billing account.
//   - departmentName - The name of the department.
//   - options - DepartmentsClientGetOptions contains the optional parameters for the DepartmentsClient.Get method.
func (client *DepartmentsClient) Get(ctx context.Context, billingAccountName string, departmentName string, options *DepartmentsClientGetOptions) (DepartmentsClientGetResponse, error) {
	var err error
	const operationName = "DepartmentsClient.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, departmentName, options)
	if err != nil {
		return DepartmentsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return DepartmentsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return DepartmentsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

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

// NewListByBillingAccountPager - Lists the departments that a user has access to. The operation is supported only for billing
// accounts with agreement type Enterprise Agreement.
//   - billingAccountName - The ID that uniquely identifies a billing account.
//   - options - DepartmentsClientListByBillingAccountOptions contains the optional parameters for the DepartmentsClient.NewListByBillingAccountPager
//     method.
func (client *DepartmentsClient) NewListByBillingAccountPager(billingAccountName string, options *DepartmentsClientListByBillingAccountOptions) *runtime.Pager[DepartmentsClientListByBillingAccountResponse] {
	return runtime.NewPager(runtime.PagingHandler[DepartmentsClientListByBillingAccountResponse]{
		More: func(page DepartmentsClientListByBillingAccountResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *DepartmentsClientListByBillingAccountResponse) (DepartmentsClientListByBillingAccountResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DepartmentsClient.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 DepartmentsClientListByBillingAccountResponse{}, err
			}
			return client.listByBillingAccountHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByBillingAccountCreateRequest creates the ListByBillingAccount request.
func (client *DepartmentsClient) listByBillingAccountCreateRequest(ctx context.Context, billingAccountName string, options *DepartmentsClientListByBillingAccountOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/departments"
	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.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 = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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