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

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

// GuestAgentsClient contains the methods for the GuestAgents group.
// Don't use this type directly, use NewGuestAgentsClient() instead.
//
// Generated from API version 2025-06-01-preview
type GuestAgentsClient struct {
	internal *arm.Client
}

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

// BeginCreate - Create Or Update GuestAgent.
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceURI - The fully qualified Azure Resource manager identifier of the resource.
//   - resource - Resource create parameters.
//   - options - GuestAgentsClientBeginCreateOptions contains the optional parameters for the GuestAgentsClient.BeginCreate method.
func (client *GuestAgentsClient) BeginCreate(ctx context.Context, resourceURI string, resource GuestAgent, options *GuestAgentsClientBeginCreateOptions) (*runtime.Poller[GuestAgentsClientCreateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.create(ctx, resourceURI, resource, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GuestAgentsClientCreateResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GuestAgentsClientCreateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Create - Create Or Update GuestAgent.
// If the operation fails it returns an *azcore.ResponseError type.
func (client *GuestAgentsClient) create(ctx context.Context, resourceURI string, resource GuestAgent, options *GuestAgentsClientBeginCreateOptions) (*http.Response, error) {
	var err error
	const operationName = "GuestAgentsClient.BeginCreate"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.createCreateRequest(ctx, resourceURI, resource, options)
	if err != nil {
		return nil, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// createCreateRequest creates the Create request.
func (client *GuestAgentsClient) createCreateRequest(ctx context.Context, resourceURI string, resource GuestAgent, _ *GuestAgentsClientBeginCreateOptions) (*policy.Request, error) {
	urlPath := "/{resourceUri}/providers/Microsoft.AzureStackHCI/virtualMachineInstances/default/guestAgents/default"
	if resourceURI == "" {
		return nil, errors.New("parameter resourceURI cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI)
	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", version20250601Preview)
	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, resource); err != nil {
		return nil, err
	}
	return req, nil
}

// BeginDelete - Implements GuestAgent DELETE method.
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceURI - The fully qualified Azure Resource manager identifier of the resource.
//   - options - GuestAgentsClientBeginDeleteOptions contains the optional parameters for the GuestAgentsClient.BeginDelete method.
func (client *GuestAgentsClient) BeginDelete(ctx context.Context, resourceURI string, options *GuestAgentsClientBeginDeleteOptions) (*runtime.Poller[GuestAgentsClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceURI, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GuestAgentsClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GuestAgentsClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Implements GuestAgent DELETE method.
// If the operation fails it returns an *azcore.ResponseError type.
func (client *GuestAgentsClient) deleteOperation(ctx context.Context, resourceURI string, options *GuestAgentsClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "GuestAgentsClient.BeginDelete"
	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, resourceURI, options)
	if err != nil {
		return nil, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// deleteCreateRequest creates the Delete request.
func (client *GuestAgentsClient) deleteCreateRequest(ctx context.Context, resourceURI string, _ *GuestAgentsClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/{resourceUri}/providers/Microsoft.AzureStackHCI/virtualMachineInstances/default/guestAgents/default"
	if resourceURI == "" {
		return nil, errors.New("parameter resourceURI cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI)
	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", version20250601Preview)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	return req, nil
}

// Get - Implements GuestAgent GET method.
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceURI - The fully qualified Azure Resource manager identifier of the resource.
//   - options - GuestAgentsClientGetOptions contains the optional parameters for the GuestAgentsClient.Get method.
func (client *GuestAgentsClient) Get(ctx context.Context, resourceURI string, options *GuestAgentsClientGetOptions) (GuestAgentsClientGetResponse, error) {
	var err error
	const operationName = "GuestAgentsClient.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, resourceURI, options)
	if err != nil {
		return GuestAgentsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return GuestAgentsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return GuestAgentsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *GuestAgentsClient) getCreateRequest(ctx context.Context, resourceURI string, _ *GuestAgentsClientGetOptions) (*policy.Request, error) {
	urlPath := "/{resourceUri}/providers/Microsoft.AzureStackHCI/virtualMachineInstances/default/guestAgents/default"
	if resourceURI == "" {
		return nil, errors.New("parameter resourceURI cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI)
	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", version20250601Preview)
	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 *GuestAgentsClient) getHandleResponse(resp *http.Response) (GuestAgentsClientGetResponse, error) {
	result := GuestAgentsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.GuestAgent); err != nil {
		return GuestAgentsClientGetResponse{}, err
	}
	return result, nil
}

// NewListByVirtualMachineInstancePager - Returns the list of GuestAgent of the given vm.
//   - resourceURI - The fully qualified Azure Resource manager identifier of the resource.
//   - options - GuestAgentsClientListByVirtualMachineInstanceOptions contains the optional parameters for the GuestAgentsClient.NewListByVirtualMachineInstancePager
//     method.
func (client *GuestAgentsClient) NewListByVirtualMachineInstancePager(resourceURI string, options *GuestAgentsClientListByVirtualMachineInstanceOptions) *runtime.Pager[GuestAgentsClientListByVirtualMachineInstanceResponse] {
	return runtime.NewPager(runtime.PagingHandler[GuestAgentsClientListByVirtualMachineInstanceResponse]{
		More: func(page GuestAgentsClientListByVirtualMachineInstanceResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *GuestAgentsClientListByVirtualMachineInstanceResponse) (GuestAgentsClientListByVirtualMachineInstanceResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GuestAgentsClient.NewListByVirtualMachineInstancePager")
			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.listByVirtualMachineInstanceCreateRequest(ctx, resourceURI, options)
			}, nil)
			if err != nil {
				return GuestAgentsClientListByVirtualMachineInstanceResponse{}, err
			}
			return client.listByVirtualMachineInstanceHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByVirtualMachineInstanceCreateRequest creates the ListByVirtualMachineInstance request.
func (client *GuestAgentsClient) listByVirtualMachineInstanceCreateRequest(ctx context.Context, resourceURI string, _ *GuestAgentsClientListByVirtualMachineInstanceOptions) (*policy.Request, error) {
	urlPath := "/{resourceUri}/providers/Microsoft.AzureStackHCI/virtualMachineInstances/default/guestAgents"
	if resourceURI == "" {
		return nil, errors.New("parameter resourceURI cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI)
	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", version20250601Preview)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByVirtualMachineInstanceHandleResponse handles the ListByVirtualMachineInstance response.
func (client *GuestAgentsClient) listByVirtualMachineInstanceHandleResponse(resp *http.Response) (GuestAgentsClientListByVirtualMachineInstanceResponse, error) {
	result := GuestAgentsClientListByVirtualMachineInstanceResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.GuestAgentListResult); err != nil {
		return GuestAgentsClientListByVirtualMachineInstanceResponse{}, err
	}
	return result, nil
}
