// 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) Go Code Generator. DO NOT EDIT.

package armresourcegraph

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

// GraphQueryClient contains the methods for the GraphQuery group.
// Don't use this type directly, use NewGraphQueryClient() instead.
//
// Generated from API version 2024-04-01
type GraphQueryClient struct {
	internal       *arm.Client
	subscriptionID string
}

// NewGraphQueryClient creates a new instance of GraphQueryClient with the specified values.
//   - subscriptionID - The ID of the target subscription. The value must be an UUID.
//   - credential - used to authorize requests. Usually a credential from azidentity.
//   - options - Contains optional client configuration. Pass nil to accept the default values.
func NewGraphQueryClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GraphQueryClient, error) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &GraphQueryClient{
		subscriptionID: subscriptionID,
		internal:       cl,
	}
	return client, nil
}

// CreateOrUpdate - Create a new graph query.
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - resourceName - The name of the Graph Query resource.
//   - properties - Properties that need to be specified to create a new graph query.
//   - options - GraphQueryClientCreateOrUpdateOptions contains the optional parameters for the GraphQueryClient.CreateOrUpdate
//     method.
func (client *GraphQueryClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, properties GraphQueryResource, options *GraphQueryClientCreateOrUpdateOptions) (GraphQueryClientCreateOrUpdateResponse, error) {
	var err error
	const operationName = "GraphQueryClient.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, resourceGroupName, resourceName, properties, options)
	if err != nil {
		return GraphQueryClientCreateOrUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return GraphQueryClientCreateOrUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return GraphQueryClientCreateOrUpdateResponse{}, err
	}
	resp, err := client.createOrUpdateHandleResponse(httpResp)
	return resp, err
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *GraphQueryClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, properties GraphQueryResource, _ *GraphQueryClientCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ResourceGraph/queries/{resourceName}"
	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 resourceName == "" {
		return nil, errors.New("parameter resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName))
	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", version20240401)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	req.Raw().Header["Content-Type"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, properties); err != nil {
		return nil, err
	}
	return req, nil
}

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

// Delete - Delete a graph query.
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - resourceName - The name of the Graph Query resource.
//   - options - GraphQueryClientDeleteOptions contains the optional parameters for the GraphQueryClient.Delete method.
func (client *GraphQueryClient) Delete(ctx context.Context, resourceGroupName string, resourceName string, options *GraphQueryClientDeleteOptions) (GraphQueryClientDeleteResponse, error) {
	var err error
	const operationName = "GraphQueryClient.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, resourceGroupName, resourceName, options)
	if err != nil {
		return GraphQueryClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return GraphQueryClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return GraphQueryClientDeleteResponse{}, err
	}
	return GraphQueryClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *GraphQueryClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, _ *GraphQueryClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ResourceGraph/queries/{resourceName}"
	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 resourceName == "" {
		return nil, errors.New("parameter resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName))
	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", version20240401)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	return req, nil
}

// Get - Get a single graph query by its resourceName.
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - resourceName - The name of the Graph Query resource.
//   - options - GraphQueryClientGetOptions contains the optional parameters for the GraphQueryClient.Get method.
func (client *GraphQueryClient) Get(ctx context.Context, resourceGroupName string, resourceName string, options *GraphQueryClientGetOptions) (GraphQueryClientGetResponse, error) {
	var err error
	const operationName = "GraphQueryClient.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, resourceName, options)
	if err != nil {
		return GraphQueryClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return GraphQueryClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return GraphQueryClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *GraphQueryClient) getCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, _ *GraphQueryClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ResourceGraph/queries/{resourceName}"
	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 resourceName == "" {
		return nil, errors.New("parameter resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName))
	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", version20240401)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListPager - Get all graph queries defined within a specified subscription and resource group.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - options - GraphQueryClientListOptions contains the optional parameters for the GraphQueryClient.NewListPager method.
func (client *GraphQueryClient) NewListPager(resourceGroupName string, options *GraphQueryClientListOptions) *runtime.Pager[GraphQueryClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[GraphQueryClientListResponse]{
		More: func(page GraphQueryClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *GraphQueryClientListResponse) (GraphQueryClientListResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GraphQueryClient.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, options)
			}, nil)
			if err != nil {
				return GraphQueryClientListResponse{}, err
			}
			return client.listHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listCreateRequest creates the List request.
func (client *GraphQueryClient) listCreateRequest(ctx context.Context, resourceGroupName string, _ *GraphQueryClientListOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ResourceGraph/queries"
	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))
	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", version20240401)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListBySubscriptionPager - Get all graph queries defined within a specified subscription.
//   - options - GraphQueryClientListBySubscriptionOptions contains the optional parameters for the GraphQueryClient.NewListBySubscriptionPager
//     method.
func (client *GraphQueryClient) NewListBySubscriptionPager(options *GraphQueryClientListBySubscriptionOptions) *runtime.Pager[GraphQueryClientListBySubscriptionResponse] {
	return runtime.NewPager(runtime.PagingHandler[GraphQueryClientListBySubscriptionResponse]{
		More: func(page GraphQueryClientListBySubscriptionResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *GraphQueryClientListBySubscriptionResponse) (GraphQueryClientListBySubscriptionResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GraphQueryClient.NewListBySubscriptionPager")
			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.listBySubscriptionCreateRequest(ctx, options)
			}, nil)
			if err != nil {
				return GraphQueryClientListBySubscriptionResponse{}, err
			}
			return client.listBySubscriptionHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listBySubscriptionCreateRequest creates the ListBySubscription request.
func (client *GraphQueryClient) listBySubscriptionCreateRequest(ctx context.Context, _ *GraphQueryClientListBySubscriptionOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ResourceGraph/queries"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	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", version20240401)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listBySubscriptionHandleResponse handles the ListBySubscription response.
func (client *GraphQueryClient) listBySubscriptionHandleResponse(resp *http.Response) (GraphQueryClientListBySubscriptionResponse, error) {
	result := GraphQueryClientListBySubscriptionResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.GraphQueryListResult); err != nil {
		return GraphQueryClientListBySubscriptionResponse{}, err
	}
	return result, nil
}

// Update - Updates a graph query that has already been added.
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - resourceName - The name of the Graph Query resource.
//   - body - Properties that need to be specified to create a new graph query.
//   - options - GraphQueryClientUpdateOptions contains the optional parameters for the GraphQueryClient.Update method.
func (client *GraphQueryClient) Update(ctx context.Context, resourceGroupName string, resourceName string, body GraphQueryUpdateParameters, options *GraphQueryClientUpdateOptions) (GraphQueryClientUpdateResponse, error) {
	var err error
	const operationName = "GraphQueryClient.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, resourceGroupName, resourceName, body, options)
	if err != nil {
		return GraphQueryClientUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return GraphQueryClientUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return GraphQueryClientUpdateResponse{}, err
	}
	resp, err := client.updateHandleResponse(httpResp)
	return resp, err
}

// updateCreateRequest creates the Update request.
func (client *GraphQueryClient) updateCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, body GraphQueryUpdateParameters, _ *GraphQueryClientUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ResourceGraph/queries/{resourceName}"
	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 resourceName == "" {
		return nil, errors.New("parameter resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName))
	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", version20240401)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	req.Raw().Header["Content-Type"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, body); err != nil {
		return nil, err
	}
	return req, nil
}

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