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

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

// BuildsClient contains the methods for the Builds group.
// Don't use this type directly, use NewBuildsClient() instead.
type BuildsClient struct {
	internal       *arm.Client
	subscriptionID string
}

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

// BeginCreateOrUpdate - Create a BuildResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-02-02-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - builderName - The name of the builder.
//   - buildName - The name of a build.
//   - buildEnvelope - Resource create or update parameters.
//   - options - BuildsClientBeginCreateOrUpdateOptions contains the optional parameters for the BuildsClient.BeginCreateOrUpdate
//     method.
func (client *BuildsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, builderName string, buildName string, buildEnvelope BuildResource, options *BuildsClientBeginCreateOrUpdateOptions) (*runtime.Poller[BuildsClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceGroupName, builderName, buildName, buildEnvelope, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[BuildsClientCreateOrUpdateResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[BuildsClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Create a BuildResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-02-02-preview
func (client *BuildsClient) createOrUpdate(ctx context.Context, resourceGroupName string, builderName string, buildName string, buildEnvelope BuildResource, options *BuildsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "BuildsClient.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, builderName, buildName, buildEnvelope, 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 *BuildsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, builderName string, buildName string, buildEnvelope BuildResource, _ *BuildsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/builders/{builderName}/builds/{buildName}"
	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 builderName == "" {
		return nil, errors.New("parameter builderName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{builderName}", url.PathEscape(builderName))
	if buildName == "" {
		return nil, errors.New("parameter buildName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{buildName}", url.PathEscape(buildName))
	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", "2025-02-02-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, buildEnvelope); err != nil {
		return nil, err
	}
	return req, nil
}

// BeginDelete - Delete a BuildResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-02-02-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - builderName - The name of the builder.
//   - buildName - The name of a build.
//   - options - BuildsClientBeginDeleteOptions contains the optional parameters for the BuildsClient.BeginDelete method.
func (client *BuildsClient) BeginDelete(ctx context.Context, resourceGroupName string, builderName string, buildName string, options *BuildsClientBeginDeleteOptions) (*runtime.Poller[BuildsClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, builderName, buildName, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[BuildsClientDeleteResponse]{
			FinalStateVia: runtime.FinalStateViaLocation,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[BuildsClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Delete a BuildResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-02-02-preview
func (client *BuildsClient) deleteOperation(ctx context.Context, resourceGroupName string, builderName string, buildName string, options *BuildsClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "BuildsClient.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, builderName, buildName, 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 *BuildsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, builderName string, buildName string, _ *BuildsClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/builders/{builderName}/builds/{buildName}"
	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 builderName == "" {
		return nil, errors.New("parameter builderName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{builderName}", url.PathEscape(builderName))
	if buildName == "" {
		return nil, errors.New("parameter buildName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{buildName}", url.PathEscape(buildName))
	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", "2025-02-02-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Get a BuildResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-02-02-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - builderName - The name of the builder.
//   - buildName - The name of a build.
//   - options - BuildsClientGetOptions contains the optional parameters for the BuildsClient.Get method.
func (client *BuildsClient) Get(ctx context.Context, resourceGroupName string, builderName string, buildName string, options *BuildsClientGetOptions) (BuildsClientGetResponse, error) {
	var err error
	const operationName = "BuildsClient.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, builderName, buildName, options)
	if err != nil {
		return BuildsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return BuildsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return BuildsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *BuildsClient) getCreateRequest(ctx context.Context, resourceGroupName string, builderName string, buildName string, _ *BuildsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/builders/{builderName}/builds/{buildName}"
	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 builderName == "" {
		return nil, errors.New("parameter builderName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{builderName}", url.PathEscape(builderName))
	if buildName == "" {
		return nil, errors.New("parameter buildName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{buildName}", url.PathEscape(buildName))
	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", "2025-02-02-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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