//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.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

package armkeyvault

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"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"
)

// KeysClient contains the methods for the Keys group.
// Don't use this type directly, use NewKeysClient() instead.
type KeysClient struct {
	host           string
	subscriptionID string
	pl             runtime.Pipeline
}

// NewKeysClient creates a new instance of KeysClient with the specified values.
// subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewKeysClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*KeysClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &KeysClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// CreateIfNotExist - Creates the first version of a new key if it does not exist. If it already exists, then the existing
// key is returned without any write operations being performed. This API does not create subsequent
// versions, and does not update existing keys.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-11-01-preview
// resourceGroupName - The name of the resource group which contains the specified key vault.
// vaultName - The name of the key vault which contains the key to be created.
// keyName - The name of the key to be created.
// parameters - The parameters used to create the specified key.
// options - KeysClientCreateIfNotExistOptions contains the optional parameters for the KeysClient.CreateIfNotExist method.
func (client *KeysClient) CreateIfNotExist(ctx context.Context, resourceGroupName string, vaultName string, keyName string, parameters KeyCreateParameters, options *KeysClientCreateIfNotExistOptions) (KeysClientCreateIfNotExistResponse, error) {
	req, err := client.createIfNotExistCreateRequest(ctx, resourceGroupName, vaultName, keyName, parameters, options)
	if err != nil {
		return KeysClientCreateIfNotExistResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return KeysClientCreateIfNotExistResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return KeysClientCreateIfNotExistResponse{}, runtime.NewResponseError(resp)
	}
	return client.createIfNotExistHandleResponse(resp)
}

// createIfNotExistCreateRequest creates the CreateIfNotExist request.
func (client *KeysClient) createIfNotExistCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, keyName string, parameters KeyCreateParameters, options *KeysClientCreateIfNotExistOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}"
	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 vaultName == "" {
		return nil, errors.New("parameter vaultName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName))
	if keyName == "" {
		return nil, errors.New("parameter keyName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{keyName}", url.PathEscape(keyName))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, parameters)
}

// createIfNotExistHandleResponse handles the CreateIfNotExist response.
func (client *KeysClient) createIfNotExistHandleResponse(resp *http.Response) (KeysClientCreateIfNotExistResponse, error) {
	result := KeysClientCreateIfNotExistResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Key); err != nil {
		return KeysClientCreateIfNotExistResponse{}, err
	}
	return result, nil
}

// Get - Gets the current version of the specified key from the specified key vault.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-11-01-preview
// resourceGroupName - The name of the resource group which contains the specified key vault.
// vaultName - The name of the vault which contains the key to be retrieved.
// keyName - The name of the key to be retrieved.
// options - KeysClientGetOptions contains the optional parameters for the KeysClient.Get method.
func (client *KeysClient) Get(ctx context.Context, resourceGroupName string, vaultName string, keyName string, options *KeysClientGetOptions) (KeysClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, resourceGroupName, vaultName, keyName, options)
	if err != nil {
		return KeysClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return KeysClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return KeysClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *KeysClient) getCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, keyName string, options *KeysClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}"
	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 vaultName == "" {
		return nil, errors.New("parameter vaultName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName))
	if keyName == "" {
		return nil, errors.New("parameter keyName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{keyName}", url.PathEscape(keyName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-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 *KeysClient) getHandleResponse(resp *http.Response) (KeysClientGetResponse, error) {
	result := KeysClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Key); err != nil {
		return KeysClientGetResponse{}, err
	}
	return result, nil
}

// GetVersion - Gets the specified version of the specified key in the specified key vault.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-11-01-preview
// resourceGroupName - The name of the resource group which contains the specified key vault.
// vaultName - The name of the vault which contains the key version to be retrieved.
// keyName - The name of the key version to be retrieved.
// keyVersion - The version of the key to be retrieved.
// options - KeysClientGetVersionOptions contains the optional parameters for the KeysClient.GetVersion method.
func (client *KeysClient) GetVersion(ctx context.Context, resourceGroupName string, vaultName string, keyName string, keyVersion string, options *KeysClientGetVersionOptions) (KeysClientGetVersionResponse, error) {
	req, err := client.getVersionCreateRequest(ctx, resourceGroupName, vaultName, keyName, keyVersion, options)
	if err != nil {
		return KeysClientGetVersionResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return KeysClientGetVersionResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return KeysClientGetVersionResponse{}, runtime.NewResponseError(resp)
	}
	return client.getVersionHandleResponse(resp)
}

// getVersionCreateRequest creates the GetVersion request.
func (client *KeysClient) getVersionCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, keyName string, keyVersion string, options *KeysClientGetVersionOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}/versions/{keyVersion}"
	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 vaultName == "" {
		return nil, errors.New("parameter vaultName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName))
	if keyName == "" {
		return nil, errors.New("parameter keyName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{keyName}", url.PathEscape(keyName))
	if keyVersion == "" {
		return nil, errors.New("parameter keyVersion cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{keyVersion}", url.PathEscape(keyVersion))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getVersionHandleResponse handles the GetVersion response.
func (client *KeysClient) getVersionHandleResponse(resp *http.Response) (KeysClientGetVersionResponse, error) {
	result := KeysClientGetVersionResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Key); err != nil {
		return KeysClientGetVersionResponse{}, err
	}
	return result, nil
}

// NewListPager - Lists the keys in the specified key vault.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-11-01-preview
// resourceGroupName - The name of the resource group which contains the specified key vault.
// vaultName - The name of the vault which contains the keys to be retrieved.
// options - KeysClientListOptions contains the optional parameters for the KeysClient.List method.
func (client *KeysClient) NewListPager(resourceGroupName string, vaultName string, options *KeysClientListOptions) *runtime.Pager[KeysClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[KeysClientListResponse]{
		More: func(page KeysClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *KeysClientListResponse) (KeysClientListResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listCreateRequest(ctx, resourceGroupName, vaultName, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return KeysClientListResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return KeysClientListResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return KeysClientListResponse{}, runtime.NewResponseError(resp)
			}
			return client.listHandleResponse(resp)
		},
	})
}

// listCreateRequest creates the List request.
func (client *KeysClient) listCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, options *KeysClientListOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys"
	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 vaultName == "" {
		return nil, errors.New("parameter vaultName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-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 *KeysClient) listHandleResponse(resp *http.Response) (KeysClientListResponse, error) {
	result := KeysClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.KeyListResult); err != nil {
		return KeysClientListResponse{}, err
	}
	return result, nil
}

// NewListVersionsPager - Lists the versions of the specified key in the specified key vault.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-11-01-preview
// resourceGroupName - The name of the resource group which contains the specified key vault.
// vaultName - The name of the vault which contains the key versions to be retrieved.
// keyName - The name of the key versions to be retrieved.
// options - KeysClientListVersionsOptions contains the optional parameters for the KeysClient.ListVersions method.
func (client *KeysClient) NewListVersionsPager(resourceGroupName string, vaultName string, keyName string, options *KeysClientListVersionsOptions) *runtime.Pager[KeysClientListVersionsResponse] {
	return runtime.NewPager(runtime.PagingHandler[KeysClientListVersionsResponse]{
		More: func(page KeysClientListVersionsResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *KeysClientListVersionsResponse) (KeysClientListVersionsResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listVersionsCreateRequest(ctx, resourceGroupName, vaultName, keyName, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return KeysClientListVersionsResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return KeysClientListVersionsResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return KeysClientListVersionsResponse{}, runtime.NewResponseError(resp)
			}
			return client.listVersionsHandleResponse(resp)
		},
	})
}

// listVersionsCreateRequest creates the ListVersions request.
func (client *KeysClient) listVersionsCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, keyName string, options *KeysClientListVersionsOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}/versions"
	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 vaultName == "" {
		return nil, errors.New("parameter vaultName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName))
	if keyName == "" {
		return nil, errors.New("parameter keyName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{keyName}", url.PathEscape(keyName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listVersionsHandleResponse handles the ListVersions response.
func (client *KeysClient) listVersionsHandleResponse(resp *http.Response) (KeysClientListVersionsResponse, error) {
	result := KeysClientListVersionsResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.KeyListResult); err != nil {
		return KeysClientListVersionsResponse{}, err
	}
	return result, nil
}
