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

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

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

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

// CreateOrUpdate - Create or update blueprint artifact.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2018-11-01-preview
//   - resourceScope - The scope of the resource. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'),
//     subscription (format: '/subscriptions/{subscriptionId}').
//   - blueprintName - Name of the blueprint definition.
//   - artifactName - Name of the blueprint artifact.
//   - artifact - Blueprint artifact to create or update.
//   - options - ArtifactsClientCreateOrUpdateOptions contains the optional parameters for the ArtifactsClient.CreateOrUpdate
//     method.
func (client *ArtifactsClient) CreateOrUpdate(ctx context.Context, resourceScope string, blueprintName string, artifactName string, artifact ArtifactClassification, options *ArtifactsClientCreateOrUpdateOptions) (ArtifactsClientCreateOrUpdateResponse, error) {
	var err error
	const operationName = "ArtifactsClient.CreateOrUpdate"
	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, resourceScope, blueprintName, artifactName, artifact, options)
	if err != nil {
		return ArtifactsClientCreateOrUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ArtifactsClientCreateOrUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return ArtifactsClientCreateOrUpdateResponse{}, err
	}
	resp, err := client.createOrUpdateHandleResponse(httpResp)
	return resp, err
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *ArtifactsClient) createOrUpdateCreateRequest(ctx context.Context, resourceScope string, blueprintName string, artifactName string, artifact ArtifactClassification, options *ArtifactsClientCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/{resourceScope}/providers/Microsoft.Blueprint/blueprints/{blueprintName}/artifacts/{artifactName}"
	urlPath = strings.ReplaceAll(urlPath, "{resourceScope}", resourceScope)
	if blueprintName == "" {
		return nil, errors.New("parameter blueprintName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{blueprintName}", url.PathEscape(blueprintName))
	if artifactName == "" {
		return nil, errors.New("parameter artifactName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{artifactName}", url.PathEscape(artifactName))
	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", "2018-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, artifact); err != nil {
		return nil, err
	}
	return req, nil
}

// createOrUpdateHandleResponse handles the CreateOrUpdate response.
func (client *ArtifactsClient) createOrUpdateHandleResponse(resp *http.Response) (ArtifactsClientCreateOrUpdateResponse, error) {
	result := ArtifactsClientCreateOrUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result); err != nil {
		return ArtifactsClientCreateOrUpdateResponse{}, err
	}
	return result, nil
}

// Delete - Delete a blueprint artifact.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2018-11-01-preview
//   - resourceScope - The scope of the resource. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'),
//     subscription (format: '/subscriptions/{subscriptionId}').
//   - blueprintName - Name of the blueprint definition.
//   - artifactName - Name of the blueprint artifact.
//   - options - ArtifactsClientDeleteOptions contains the optional parameters for the ArtifactsClient.Delete method.
func (client *ArtifactsClient) Delete(ctx context.Context, resourceScope string, blueprintName string, artifactName string, options *ArtifactsClientDeleteOptions) (ArtifactsClientDeleteResponse, error) {
	var err error
	const operationName = "ArtifactsClient.Delete"
	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, resourceScope, blueprintName, artifactName, options)
	if err != nil {
		return ArtifactsClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ArtifactsClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return ArtifactsClientDeleteResponse{}, err
	}
	resp, err := client.deleteHandleResponse(httpResp)
	return resp, err
}

// deleteCreateRequest creates the Delete request.
func (client *ArtifactsClient) deleteCreateRequest(ctx context.Context, resourceScope string, blueprintName string, artifactName string, options *ArtifactsClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/{resourceScope}/providers/Microsoft.Blueprint/blueprints/{blueprintName}/artifacts/{artifactName}"
	urlPath = strings.ReplaceAll(urlPath, "{resourceScope}", resourceScope)
	if blueprintName == "" {
		return nil, errors.New("parameter blueprintName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{blueprintName}", url.PathEscape(blueprintName))
	if artifactName == "" {
		return nil, errors.New("parameter artifactName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{artifactName}", url.PathEscape(artifactName))
	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", "2018-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// deleteHandleResponse handles the Delete response.
func (client *ArtifactsClient) deleteHandleResponse(resp *http.Response) (ArtifactsClientDeleteResponse, error) {
	result := ArtifactsClientDeleteResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result); err != nil {
		return ArtifactsClientDeleteResponse{}, err
	}
	return result, nil
}

// Get - Get a blueprint artifact.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2018-11-01-preview
//   - resourceScope - The scope of the resource. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'),
//     subscription (format: '/subscriptions/{subscriptionId}').
//   - blueprintName - Name of the blueprint definition.
//   - artifactName - Name of the blueprint artifact.
//   - options - ArtifactsClientGetOptions contains the optional parameters for the ArtifactsClient.Get method.
func (client *ArtifactsClient) Get(ctx context.Context, resourceScope string, blueprintName string, artifactName string, options *ArtifactsClientGetOptions) (ArtifactsClientGetResponse, error) {
	var err error
	const operationName = "ArtifactsClient.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, resourceScope, blueprintName, artifactName, options)
	if err != nil {
		return ArtifactsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ArtifactsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return ArtifactsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *ArtifactsClient) getCreateRequest(ctx context.Context, resourceScope string, blueprintName string, artifactName string, options *ArtifactsClientGetOptions) (*policy.Request, error) {
	urlPath := "/{resourceScope}/providers/Microsoft.Blueprint/blueprints/{blueprintName}/artifacts/{artifactName}"
	urlPath = strings.ReplaceAll(urlPath, "{resourceScope}", resourceScope)
	if blueprintName == "" {
		return nil, errors.New("parameter blueprintName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{blueprintName}", url.PathEscape(blueprintName))
	if artifactName == "" {
		return nil, errors.New("parameter artifactName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{artifactName}", url.PathEscape(artifactName))
	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", "2018-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListPager - List artifacts for a given blueprint definition.
//
// Generated from API version 2018-11-01-preview
//   - resourceScope - The scope of the resource. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'),
//     subscription (format: '/subscriptions/{subscriptionId}').
//   - blueprintName - Name of the blueprint definition.
//   - options - ArtifactsClientListOptions contains the optional parameters for the ArtifactsClient.NewListPager method.
func (client *ArtifactsClient) NewListPager(resourceScope string, blueprintName string, options *ArtifactsClientListOptions) *runtime.Pager[ArtifactsClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[ArtifactsClientListResponse]{
		More: func(page ArtifactsClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *ArtifactsClientListResponse) (ArtifactsClientListResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ArtifactsClient.NewListPager")
			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.listCreateRequest(ctx, resourceScope, blueprintName, options)
			}, nil)
			if err != nil {
				return ArtifactsClientListResponse{}, err
			}
			return client.listHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listCreateRequest creates the List request.
func (client *ArtifactsClient) listCreateRequest(ctx context.Context, resourceScope string, blueprintName string, options *ArtifactsClientListOptions) (*policy.Request, error) {
	urlPath := "/{resourceScope}/providers/Microsoft.Blueprint/blueprints/{blueprintName}/artifacts"
	urlPath = strings.ReplaceAll(urlPath, "{resourceScope}", resourceScope)
	if blueprintName == "" {
		return nil, errors.New("parameter blueprintName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{blueprintName}", url.PathEscape(blueprintName))
	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", "2018-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listHandleResponse handles the List response.
func (client *ArtifactsClient) listHandleResponse(resp *http.Response) (ArtifactsClientListResponse, error) {
	result := ArtifactsClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ArtifactList); err != nil {
		return ArtifactsClientListResponse{}, err
	}
	return result, nil
}
