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

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

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

// 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) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &KeysClient{
		subscriptionID: subscriptionID,
		internal:       cl,
	}
	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 2024-11-01
//   - 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. The value you provide may be copied globally for the purpose of running the
//     service. The value provided should not include personally identifiable or sensitive
//     information.
//   - 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) {
	var err error
	const operationName = "KeysClient.CreateIfNotExist"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.createIfNotExistCreateRequest(ctx, resourceGroupName, vaultName, keyName, parameters, options)
	if err != nil {
		return KeysClientCreateIfNotExistResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return KeysClientCreateIfNotExistResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return KeysClientCreateIfNotExistResponse{}, err
	}
	resp, err := client.createIfNotExistHandleResponse(httpResp)
	return resp, err
}

// createIfNotExistCreateRequest creates the CreateIfNotExist request.
func (client *KeysClient) createIfNotExistCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, keyName string, parameters KeyCreateParameters, _ *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.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-11-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, parameters); err != nil {
		return nil, err
	}
	return req, nil
}

// 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 2024-11-01
//   - 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) {
	var err error
	const operationName = "KeysClient.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, vaultName, keyName, options)
	if err != nil {
		return KeysClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return KeysClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return KeysClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *KeysClient) getCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, keyName string, _ *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.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-11-01")
	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 2024-11-01
//   - 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) {
	var err error
	const operationName = "KeysClient.GetVersion"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.getVersionCreateRequest(ctx, resourceGroupName, vaultName, keyName, keyVersion, options)
	if err != nil {
		return KeysClientGetVersionResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return KeysClientGetVersionResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return KeysClientGetVersionResponse{}, err
	}
	resp, err := client.getVersionHandleResponse(httpResp)
	return resp, err
}

// getVersionCreateRequest creates the GetVersion request.
func (client *KeysClient) getVersionCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, keyName string, keyVersion string, _ *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.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-11-01")
	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.
//
// Generated from API version 2024-11-01
//   - 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.NewListPager 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) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "KeysClient.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, resourceGroupName, vaultName, options)
			}, nil)
			if err != nil {
				return KeysClientListResponse{}, err
			}
			return client.listHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listCreateRequest creates the List request.
func (client *KeysClient) listCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, _ *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.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-11-01")
	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.
//
// Generated from API version 2024-11-01
//   - 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.NewListVersionsPager 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) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "KeysClient.NewListVersionsPager")
			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.listVersionsCreateRequest(ctx, resourceGroupName, vaultName, keyName, options)
			}, nil)
			if err != nil {
				return KeysClientListVersionsResponse{}, err
			}
			return client.listVersionsHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listVersionsCreateRequest creates the ListVersions request.
func (client *KeysClient) listVersionsCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, keyName string, _ *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.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-11-01")
	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
}
