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

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

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

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

// CreateOrUpdate - Create a new AppComplianceAutomation webhook or update an exiting AppComplianceAutomation webhook.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-06-27
//   - reportName - Report Name.
//   - webhookName - Webhook Name.
//   - properties - Parameters for the create or update operation
//   - options - WebhookClientCreateOrUpdateOptions contains the optional parameters for the WebhookClient.CreateOrUpdate method.
func (client *WebhookClient) CreateOrUpdate(ctx context.Context, reportName string, webhookName string, properties WebhookResource, options *WebhookClientCreateOrUpdateOptions) (WebhookClientCreateOrUpdateResponse, error) {
	var err error
	const operationName = "WebhookClient.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, reportName, webhookName, properties, options)
	if err != nil {
		return WebhookClientCreateOrUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return WebhookClientCreateOrUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return WebhookClientCreateOrUpdateResponse{}, err
	}
	resp, err := client.createOrUpdateHandleResponse(httpResp)
	return resp, err
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *WebhookClient) createOrUpdateCreateRequest(ctx context.Context, reportName string, webhookName string, properties WebhookResource, options *WebhookClientCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.AppComplianceAutomation/reports/{reportName}/webhooks/{webhookName}"
	if reportName == "" {
		return nil, errors.New("parameter reportName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{reportName}", url.PathEscape(reportName))
	if webhookName == "" {
		return nil, errors.New("parameter webhookName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{webhookName}", url.PathEscape(webhookName))
	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-06-27")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, properties); err != nil {
		return nil, err
	}
	return req, nil
}

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

// Delete - Delete an AppComplianceAutomation webhook.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-06-27
//   - reportName - Report Name.
//   - webhookName - Webhook Name.
//   - options - WebhookClientDeleteOptions contains the optional parameters for the WebhookClient.Delete method.
func (client *WebhookClient) Delete(ctx context.Context, reportName string, webhookName string, options *WebhookClientDeleteOptions) (WebhookClientDeleteResponse, error) {
	var err error
	const operationName = "WebhookClient.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, reportName, webhookName, options)
	if err != nil {
		return WebhookClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return WebhookClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return WebhookClientDeleteResponse{}, err
	}
	return WebhookClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *WebhookClient) deleteCreateRequest(ctx context.Context, reportName string, webhookName string, options *WebhookClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.AppComplianceAutomation/reports/{reportName}/webhooks/{webhookName}"
	if reportName == "" {
		return nil, errors.New("parameter reportName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{reportName}", url.PathEscape(reportName))
	if webhookName == "" {
		return nil, errors.New("parameter webhookName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{webhookName}", url.PathEscape(webhookName))
	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", "2024-06-27")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Get the AppComplianceAutomation webhook and its properties.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-06-27
//   - reportName - Report Name.
//   - webhookName - Webhook Name.
//   - options - WebhookClientGetOptions contains the optional parameters for the WebhookClient.Get method.
func (client *WebhookClient) Get(ctx context.Context, reportName string, webhookName string, options *WebhookClientGetOptions) (WebhookClientGetResponse, error) {
	var err error
	const operationName = "WebhookClient.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, reportName, webhookName, options)
	if err != nil {
		return WebhookClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return WebhookClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return WebhookClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *WebhookClient) getCreateRequest(ctx context.Context, reportName string, webhookName string, options *WebhookClientGetOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.AppComplianceAutomation/reports/{reportName}/webhooks/{webhookName}"
	if reportName == "" {
		return nil, errors.New("parameter reportName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{reportName}", url.PathEscape(reportName))
	if webhookName == "" {
		return nil, errors.New("parameter webhookName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{webhookName}", url.PathEscape(webhookName))
	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-06-27")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListPager - Get the AppComplianceAutomation webhook list.
//
// Generated from API version 2024-06-27
//   - reportName - Report Name.
//   - options - WebhookClientListOptions contains the optional parameters for the WebhookClient.NewListPager method.
func (client *WebhookClient) NewListPager(reportName string, options *WebhookClientListOptions) *runtime.Pager[WebhookClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[WebhookClientListResponse]{
		More: func(page WebhookClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *WebhookClientListResponse) (WebhookClientListResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WebhookClient.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, reportName, options)
			}, nil)
			if err != nil {
				return WebhookClientListResponse{}, err
			}
			return client.listHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listCreateRequest creates the List request.
func (client *WebhookClient) listCreateRequest(ctx context.Context, reportName string, options *WebhookClientListOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.AppComplianceAutomation/reports/{reportName}/webhooks"
	if reportName == "" {
		return nil, errors.New("parameter reportName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{reportName}", url.PathEscape(reportName))
	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.Orderby != nil {
		reqQP.Set("$orderby", *options.Orderby)
	}
	if options != nil && options.Select != nil {
		reqQP.Set("$select", *options.Select)
	}
	if options != nil && options.SkipToken != nil {
		reqQP.Set("$skipToken", *options.SkipToken)
	}
	if options != nil && options.Top != nil {
		reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10))
	}
	reqQP.Set("api-version", "2024-06-27")
	if options != nil && options.OfferGUID != nil {
		reqQP.Set("offerGuid", *options.OfferGUID)
	}
	if options != nil && options.ReportCreatorTenantID != nil {
		reqQP.Set("reportCreatorTenantId", *options.ReportCreatorTenantID)
	}
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// Update - Update an exiting AppComplianceAutomation webhook.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-06-27
//   - reportName - Report Name.
//   - webhookName - Webhook Name.
//   - properties - Parameters for the create or update operation
//   - options - WebhookClientUpdateOptions contains the optional parameters for the WebhookClient.Update method.
func (client *WebhookClient) Update(ctx context.Context, reportName string, webhookName string, properties WebhookResourcePatch, options *WebhookClientUpdateOptions) (WebhookClientUpdateResponse, error) {
	var err error
	const operationName = "WebhookClient.Update"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.updateCreateRequest(ctx, reportName, webhookName, properties, options)
	if err != nil {
		return WebhookClientUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return WebhookClientUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return WebhookClientUpdateResponse{}, err
	}
	resp, err := client.updateHandleResponse(httpResp)
	return resp, err
}

// updateCreateRequest creates the Update request.
func (client *WebhookClient) updateCreateRequest(ctx context.Context, reportName string, webhookName string, properties WebhookResourcePatch, options *WebhookClientUpdateOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.AppComplianceAutomation/reports/{reportName}/webhooks/{webhookName}"
	if reportName == "" {
		return nil, errors.New("parameter reportName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{reportName}", url.PathEscape(reportName))
	if webhookName == "" {
		return nil, errors.New("parameter webhookName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{webhookName}", url.PathEscape(webhookName))
	req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-06-27")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, properties); err != nil {
		return nil, err
	}
	return req, nil
}

// updateHandleResponse handles the Update response.
func (client *WebhookClient) updateHandleResponse(resp *http.Response) (WebhookClientUpdateResponse, error) {
	result := WebhookClientUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.WebhookResource); err != nil {
		return WebhookClientUpdateResponse{}, err
	}
	return result, nil
}
