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

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

// WorkflowsClient contains the methods for the Workflows group.
// Don't use this type directly, use NewWorkflowsClient() instead.
//
// Generated from API version 2025-06-01
type WorkflowsClient struct {
	internal       *arm.Client
	subscriptionID string
}

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

// BeginCreateOrUpdate - Create or update a Workflow resource
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - contextName - The name of the Context.
//   - workflowName - Name of the workflow
//   - resource - Resource create parameters.
//   - options - WorkflowsClientBeginCreateOrUpdateOptions contains the optional parameters for the WorkflowsClient.BeginCreateOrUpdate
//     method.
func (client *WorkflowsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, contextName string, workflowName string, resource Workflow, options *WorkflowsClientBeginCreateOrUpdateOptions) (*runtime.Poller[WorkflowsClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceGroupName, contextName, workflowName, resource, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WorkflowsClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WorkflowsClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Create or update a Workflow resource
// If the operation fails it returns an *azcore.ResponseError type.
func (client *WorkflowsClient) createOrUpdate(ctx context.Context, resourceGroupName string, contextName string, workflowName string, resource Workflow, options *WorkflowsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "WorkflowsClient.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, contextName, workflowName, 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 *WorkflowsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, contextName string, workflowName string, resource Workflow, _ *WorkflowsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Edge/contexts/{contextName}/workflows/{workflowName}"
	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 contextName == "" {
		return nil, errors.New("parameter contextName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{contextName}", url.PathEscape(contextName))
	if workflowName == "" {
		return nil, errors.New("parameter workflowName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{workflowName}", url.PathEscape(workflowName))
	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", version20250601)
	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 Workflow resource
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - contextName - The name of the Context.
//   - workflowName - Name of the workflow
//   - options - WorkflowsClientBeginDeleteOptions contains the optional parameters for the WorkflowsClient.BeginDelete method.
func (client *WorkflowsClient) BeginDelete(ctx context.Context, resourceGroupName string, contextName string, workflowName string, options *WorkflowsClientBeginDeleteOptions) (*runtime.Poller[WorkflowsClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, contextName, workflowName, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WorkflowsClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WorkflowsClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Delete a Workflow resource
// If the operation fails it returns an *azcore.ResponseError type.
func (client *WorkflowsClient) deleteOperation(ctx context.Context, resourceGroupName string, contextName string, workflowName string, options *WorkflowsClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "WorkflowsClient.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, contextName, workflowName, 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 *WorkflowsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, contextName string, workflowName string, _ *WorkflowsClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Edge/contexts/{contextName}/workflows/{workflowName}"
	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 contextName == "" {
		return nil, errors.New("parameter contextName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{contextName}", url.PathEscape(contextName))
	if workflowName == "" {
		return nil, errors.New("parameter workflowName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{workflowName}", url.PathEscape(workflowName))
	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", version20250601)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	return req, nil
}

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

// getCreateRequest creates the Get request.
func (client *WorkflowsClient) getCreateRequest(ctx context.Context, resourceGroupName string, contextName string, workflowName string, _ *WorkflowsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Edge/contexts/{contextName}/workflows/{workflowName}"
	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 contextName == "" {
		return nil, errors.New("parameter contextName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{contextName}", url.PathEscape(contextName))
	if workflowName == "" {
		return nil, errors.New("parameter workflowName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{workflowName}", url.PathEscape(workflowName))
	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", version20250601)
	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 *WorkflowsClient) getHandleResponse(resp *http.Response) (WorkflowsClientGetResponse, error) {
	result := WorkflowsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Workflow); err != nil {
		return WorkflowsClientGetResponse{}, err
	}
	return result, nil
}

// NewListByContextPager - List Workflow resources
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - contextName - The name of the Context.
//   - options - WorkflowsClientListByContextOptions contains the optional parameters for the WorkflowsClient.NewListByContextPager
//     method.
func (client *WorkflowsClient) NewListByContextPager(resourceGroupName string, contextName string, options *WorkflowsClientListByContextOptions) *runtime.Pager[WorkflowsClientListByContextResponse] {
	return runtime.NewPager(runtime.PagingHandler[WorkflowsClientListByContextResponse]{
		More: func(page WorkflowsClientListByContextResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *WorkflowsClientListByContextResponse) (WorkflowsClientListByContextResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WorkflowsClient.NewListByContextPager")
			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.listByContextCreateRequest(ctx, resourceGroupName, contextName, options)
			}, nil)
			if err != nil {
				return WorkflowsClientListByContextResponse{}, err
			}
			return client.listByContextHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByContextCreateRequest creates the ListByContext request.
func (client *WorkflowsClient) listByContextCreateRequest(ctx context.Context, resourceGroupName string, contextName string, _ *WorkflowsClientListByContextOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Edge/contexts/{contextName}/workflows"
	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 contextName == "" {
		return nil, errors.New("parameter contextName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{contextName}", url.PathEscape(contextName))
	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", version20250601)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByContextHandleResponse handles the ListByContext response.
func (client *WorkflowsClient) listByContextHandleResponse(resp *http.Response) (WorkflowsClientListByContextResponse, error) {
	result := WorkflowsClientListByContextResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.WorkflowListResult); err != nil {
		return WorkflowsClientListByContextResponse{}, err
	}
	return result, nil
}

// BeginUpdate - update a Workflow resource
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - contextName - The name of the Context.
//   - workflowName - Name of the workflow
//   - properties - The resource properties to be updated.
//   - options - WorkflowsClientBeginUpdateOptions contains the optional parameters for the WorkflowsClient.BeginUpdate method.
func (client *WorkflowsClient) BeginUpdate(ctx context.Context, resourceGroupName string, contextName string, workflowName string, properties Workflow, options *WorkflowsClientBeginUpdateOptions) (*runtime.Poller[WorkflowsClientUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.update(ctx, resourceGroupName, contextName, workflowName, properties, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WorkflowsClientUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WorkflowsClientUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Update - update a Workflow resource
// If the operation fails it returns an *azcore.ResponseError type.
func (client *WorkflowsClient) update(ctx context.Context, resourceGroupName string, contextName string, workflowName string, properties Workflow, options *WorkflowsClientBeginUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "WorkflowsClient.BeginUpdate"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.updateCreateRequest(ctx, resourceGroupName, contextName, workflowName, properties, 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.StatusAccepted) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// updateCreateRequest creates the Update request.
func (client *WorkflowsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, contextName string, workflowName string, properties Workflow, _ *WorkflowsClientBeginUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Edge/contexts/{contextName}/workflows/{workflowName}"
	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 contextName == "" {
		return nil, errors.New("parameter contextName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{contextName}", url.PathEscape(contextName))
	if workflowName == "" {
		return nil, errors.New("parameter workflowName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{workflowName}", url.PathEscape(workflowName))
	req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", version20250601)
	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, properties); err != nil {
		return nil, err
	}
	return req, nil
}
