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

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

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

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

// Get - Get a Certificate
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - catalogName - Name of catalog
//   - serialNumber - Serial number of the certificate. Use '.default' to get current active certificate.
//   - options - CertificatesClientGetOptions contains the optional parameters for the CertificatesClient.Get method.
func (client *CertificatesClient) Get(ctx context.Context, resourceGroupName string, catalogName string, serialNumber string, options *CertificatesClientGetOptions) (CertificatesClientGetResponse, error) {
	var err error
	const operationName = "CertificatesClient.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, catalogName, serialNumber, options)
	if err != nil {
		return CertificatesClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return CertificatesClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return CertificatesClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *CertificatesClient) getCreateRequest(ctx context.Context, resourceGroupName string, catalogName string, serialNumber string, options *CertificatesClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureSphere/catalogs/{catalogName}/certificates/{serialNumber}"
	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 catalogName == "" {
		return nil, errors.New("parameter catalogName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{catalogName}", url.PathEscape(catalogName))
	if serialNumber == "" {
		return nil, errors.New("parameter serialNumber cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serialNumber}", url.PathEscape(serialNumber))
	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-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListByCatalogPager - List Certificate resources by Catalog
//
// Generated from API version 2024-04-01
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - catalogName - Name of catalog
//   - options - CertificatesClientListByCatalogOptions contains the optional parameters for the CertificatesClient.NewListByCatalogPager
//     method.
func (client *CertificatesClient) NewListByCatalogPager(resourceGroupName string, catalogName string, options *CertificatesClientListByCatalogOptions) *runtime.Pager[CertificatesClientListByCatalogResponse] {
	return runtime.NewPager(runtime.PagingHandler[CertificatesClientListByCatalogResponse]{
		More: func(page CertificatesClientListByCatalogResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *CertificatesClientListByCatalogResponse) (CertificatesClientListByCatalogResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CertificatesClient.NewListByCatalogPager")
			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.listByCatalogCreateRequest(ctx, resourceGroupName, catalogName, options)
			}, nil)
			if err != nil {
				return CertificatesClientListByCatalogResponse{}, err
			}
			return client.listByCatalogHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByCatalogCreateRequest creates the ListByCatalog request.
func (client *CertificatesClient) listByCatalogCreateRequest(ctx context.Context, resourceGroupName string, catalogName string, options *CertificatesClientListByCatalogOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureSphere/catalogs/{catalogName}/certificates"
	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 catalogName == "" {
		return nil, errors.New("parameter catalogName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{catalogName}", url.PathEscape(catalogName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	if options != nil && options.Filter != nil {
		reqQP.Set("$filter", *options.Filter)
	}
	if options != nil && options.Maxpagesize != nil {
		reqQP.Set("$maxpagesize", strconv.FormatInt(int64(*options.Maxpagesize), 10))
	}
	if options != nil && options.Skip != nil {
		reqQP.Set("$skip", strconv.FormatInt(int64(*options.Skip), 10))
	}
	if options != nil && options.Top != nil {
		reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10))
	}
	reqQP.Set("api-version", "2024-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByCatalogHandleResponse handles the ListByCatalog response.
func (client *CertificatesClient) listByCatalogHandleResponse(resp *http.Response) (CertificatesClientListByCatalogResponse, error) {
	result := CertificatesClientListByCatalogResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CertificateListResult); err != nil {
		return CertificatesClientListByCatalogResponse{}, err
	}
	return result, nil
}

// RetrieveCertChain - Retrieves cert chain.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - catalogName - Name of catalog
//   - serialNumber - Serial number of the certificate. Use '.default' to get current active certificate.
//   - options - CertificatesClientRetrieveCertChainOptions contains the optional parameters for the CertificatesClient.RetrieveCertChain
//     method.
func (client *CertificatesClient) RetrieveCertChain(ctx context.Context, resourceGroupName string, catalogName string, serialNumber string, options *CertificatesClientRetrieveCertChainOptions) (CertificatesClientRetrieveCertChainResponse, error) {
	var err error
	const operationName = "CertificatesClient.RetrieveCertChain"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.retrieveCertChainCreateRequest(ctx, resourceGroupName, catalogName, serialNumber, options)
	if err != nil {
		return CertificatesClientRetrieveCertChainResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return CertificatesClientRetrieveCertChainResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return CertificatesClientRetrieveCertChainResponse{}, err
	}
	resp, err := client.retrieveCertChainHandleResponse(httpResp)
	return resp, err
}

// retrieveCertChainCreateRequest creates the RetrieveCertChain request.
func (client *CertificatesClient) retrieveCertChainCreateRequest(ctx context.Context, resourceGroupName string, catalogName string, serialNumber string, options *CertificatesClientRetrieveCertChainOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureSphere/catalogs/{catalogName}/certificates/{serialNumber}/retrieveCertChain"
	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 catalogName == "" {
		return nil, errors.New("parameter catalogName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{catalogName}", url.PathEscape(catalogName))
	if serialNumber == "" {
		return nil, errors.New("parameter serialNumber cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serialNumber}", url.PathEscape(serialNumber))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// retrieveCertChainHandleResponse handles the RetrieveCertChain response.
func (client *CertificatesClient) retrieveCertChainHandleResponse(resp *http.Response) (CertificatesClientRetrieveCertChainResponse, error) {
	result := CertificatesClientRetrieveCertChainResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CertificateChainResponse); err != nil {
		return CertificatesClientRetrieveCertChainResponse{}, err
	}
	return result, nil
}

// RetrieveProofOfPossessionNonce - Gets the proof of possession nonce.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - catalogName - Name of catalog
//   - serialNumber - Serial number of the certificate. Use '.default' to get current active certificate.
//   - proofOfPossessionNonceRequest - Proof of possession nonce request body
//   - options - CertificatesClientRetrieveProofOfPossessionNonceOptions contains the optional parameters for the CertificatesClient.RetrieveProofOfPossessionNonce
//     method.
func (client *CertificatesClient) RetrieveProofOfPossessionNonce(ctx context.Context, resourceGroupName string, catalogName string, serialNumber string, proofOfPossessionNonceRequest ProofOfPossessionNonceRequest, options *CertificatesClientRetrieveProofOfPossessionNonceOptions) (CertificatesClientRetrieveProofOfPossessionNonceResponse, error) {
	var err error
	const operationName = "CertificatesClient.RetrieveProofOfPossessionNonce"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.retrieveProofOfPossessionNonceCreateRequest(ctx, resourceGroupName, catalogName, serialNumber, proofOfPossessionNonceRequest, options)
	if err != nil {
		return CertificatesClientRetrieveProofOfPossessionNonceResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return CertificatesClientRetrieveProofOfPossessionNonceResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return CertificatesClientRetrieveProofOfPossessionNonceResponse{}, err
	}
	resp, err := client.retrieveProofOfPossessionNonceHandleResponse(httpResp)
	return resp, err
}

// retrieveProofOfPossessionNonceCreateRequest creates the RetrieveProofOfPossessionNonce request.
func (client *CertificatesClient) retrieveProofOfPossessionNonceCreateRequest(ctx context.Context, resourceGroupName string, catalogName string, serialNumber string, proofOfPossessionNonceRequest ProofOfPossessionNonceRequest, options *CertificatesClientRetrieveProofOfPossessionNonceOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureSphere/catalogs/{catalogName}/certificates/{serialNumber}/retrieveProofOfPossessionNonce"
	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 catalogName == "" {
		return nil, errors.New("parameter catalogName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{catalogName}", url.PathEscape(catalogName))
	if serialNumber == "" {
		return nil, errors.New("parameter serialNumber cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serialNumber}", url.PathEscape(serialNumber))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, proofOfPossessionNonceRequest); err != nil {
		return nil, err
	}
	return req, nil
}

// retrieveProofOfPossessionNonceHandleResponse handles the RetrieveProofOfPossessionNonce response.
func (client *CertificatesClient) retrieveProofOfPossessionNonceHandleResponse(resp *http.Response) (CertificatesClientRetrieveProofOfPossessionNonceResponse, error) {
	result := CertificatesClientRetrieveProofOfPossessionNonceResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ProofOfPossessionNonceResponse); err != nil {
		return CertificatesClientRetrieveProofOfPossessionNonceResponse{}, err
	}
	return result, nil
}
