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

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

// TaskHubsClient contains the methods for the TaskHubs group.
// Don't use this type directly, use NewTaskHubsClient() instead.
//
// Generated from API version 2026-02-01
type TaskHubsClient struct {
	internal       *arm.Client
	subscriptionID string
}

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

// BeginCreateOrUpdate - Create or Update a Task Hub
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - schedulerName - The name of the Scheduler
//   - taskHubName - The name of the TaskHub
//   - resource - Resource create parameters.
//   - options - TaskHubsClientBeginCreateOrUpdateOptions contains the optional parameters for the TaskHubsClient.BeginCreateOrUpdate
//     method.
func (client *TaskHubsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, schedulerName string, taskHubName string, resource TaskHub, options *TaskHubsClientBeginCreateOrUpdateOptions) (*runtime.Poller[TaskHubsClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceGroupName, schedulerName, taskHubName, resource, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TaskHubsClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TaskHubsClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Create or Update a Task Hub
// If the operation fails it returns an *azcore.ResponseError type.
func (client *TaskHubsClient) createOrUpdate(ctx context.Context, resourceGroupName string, schedulerName string, taskHubName string, resource TaskHub, options *TaskHubsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "TaskHubsClient.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, schedulerName, taskHubName, 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 *TaskHubsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, schedulerName string, taskHubName string, resource TaskHub, _ *TaskHubsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DurableTask/schedulers/{schedulerName}/taskHubs/{taskHubName}"
	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 schedulerName == "" {
		return nil, errors.New("parameter schedulerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{schedulerName}", url.PathEscape(schedulerName))
	if taskHubName == "" {
		return nil, errors.New("parameter taskHubName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{taskHubName}", url.PathEscape(taskHubName))
	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", version20260201)
	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 Task Hub
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - schedulerName - The name of the Scheduler
//   - taskHubName - The name of the TaskHub
//   - options - TaskHubsClientBeginDeleteOptions contains the optional parameters for the TaskHubsClient.BeginDelete method.
func (client *TaskHubsClient) BeginDelete(ctx context.Context, resourceGroupName string, schedulerName string, taskHubName string, options *TaskHubsClientBeginDeleteOptions) (*runtime.Poller[TaskHubsClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, schedulerName, taskHubName, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TaskHubsClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TaskHubsClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Delete a Task Hub
// If the operation fails it returns an *azcore.ResponseError type.
func (client *TaskHubsClient) deleteOperation(ctx context.Context, resourceGroupName string, schedulerName string, taskHubName string, options *TaskHubsClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "TaskHubsClient.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, schedulerName, taskHubName, 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 *TaskHubsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, schedulerName string, taskHubName string, _ *TaskHubsClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DurableTask/schedulers/{schedulerName}/taskHubs/{taskHubName}"
	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 schedulerName == "" {
		return nil, errors.New("parameter schedulerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{schedulerName}", url.PathEscape(schedulerName))
	if taskHubName == "" {
		return nil, errors.New("parameter taskHubName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{taskHubName}", url.PathEscape(taskHubName))
	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", version20260201)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	return req, nil
}

// Get - Get a Task Hub
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - schedulerName - The name of the Scheduler
//   - taskHubName - The name of the TaskHub
//   - options - TaskHubsClientGetOptions contains the optional parameters for the TaskHubsClient.Get method.
func (client *TaskHubsClient) Get(ctx context.Context, resourceGroupName string, schedulerName string, taskHubName string, options *TaskHubsClientGetOptions) (TaskHubsClientGetResponse, error) {
	var err error
	const operationName = "TaskHubsClient.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, schedulerName, taskHubName, options)
	if err != nil {
		return TaskHubsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return TaskHubsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return TaskHubsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *TaskHubsClient) getCreateRequest(ctx context.Context, resourceGroupName string, schedulerName string, taskHubName string, _ *TaskHubsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DurableTask/schedulers/{schedulerName}/taskHubs/{taskHubName}"
	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 schedulerName == "" {
		return nil, errors.New("parameter schedulerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{schedulerName}", url.PathEscape(schedulerName))
	if taskHubName == "" {
		return nil, errors.New("parameter taskHubName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{taskHubName}", url.PathEscape(taskHubName))
	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", version20260201)
	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 *TaskHubsClient) getHandleResponse(resp *http.Response) (TaskHubsClientGetResponse, error) {
	result := TaskHubsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.TaskHub); err != nil {
		return TaskHubsClientGetResponse{}, err
	}
	return result, nil
}

// NewListBySchedulerPager - List Task Hubs
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - schedulerName - The name of the Scheduler
//   - options - TaskHubsClientListBySchedulerOptions contains the optional parameters for the TaskHubsClient.NewListBySchedulerPager
//     method.
func (client *TaskHubsClient) NewListBySchedulerPager(resourceGroupName string, schedulerName string, options *TaskHubsClientListBySchedulerOptions) *runtime.Pager[TaskHubsClientListBySchedulerResponse] {
	return runtime.NewPager(runtime.PagingHandler[TaskHubsClientListBySchedulerResponse]{
		More: func(page TaskHubsClientListBySchedulerResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *TaskHubsClientListBySchedulerResponse) (TaskHubsClientListBySchedulerResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "TaskHubsClient.NewListBySchedulerPager")
			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.listBySchedulerCreateRequest(ctx, resourceGroupName, schedulerName, options)
			}, nil)
			if err != nil {
				return TaskHubsClientListBySchedulerResponse{}, err
			}
			return client.listBySchedulerHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listBySchedulerCreateRequest creates the ListByScheduler request.
func (client *TaskHubsClient) listBySchedulerCreateRequest(ctx context.Context, resourceGroupName string, schedulerName string, _ *TaskHubsClientListBySchedulerOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DurableTask/schedulers/{schedulerName}/taskHubs"
	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 schedulerName == "" {
		return nil, errors.New("parameter schedulerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{schedulerName}", url.PathEscape(schedulerName))
	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", version20260201)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listBySchedulerHandleResponse handles the ListByScheduler response.
func (client *TaskHubsClient) listBySchedulerHandleResponse(resp *http.Response) (TaskHubsClientListBySchedulerResponse, error) {
	result := TaskHubsClientListBySchedulerResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.TaskHubListResult); err != nil {
		return TaskHubsClientListBySchedulerResponse{}, err
	}
	return result, nil
}
