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

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

// MaintenanceEventsClient - Maintenance event operations for PostgreSQL flexible servers.
// Don't use this type directly, use NewMaintenanceEventsClient() instead.
//
// Generated from API version 2026-04-01-preview
type MaintenanceEventsClient struct {
	internal       *arm.Client
	subscriptionID string
}

// NewMaintenanceEventsClient creates a new instance of MaintenanceEventsClient 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 NewMaintenanceEventsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*MaintenanceEventsClient, error) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &MaintenanceEventsClient{
		subscriptionID: subscriptionID,
		internal:       cl,
	}
	return client, nil
}

// BeginApplyNow - Applies the maintenance event immediately.
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - serverName - The name of the server.
//   - maintenanceEventID - The name of the MaintenanceEventResource
//   - options - MaintenanceEventsClientBeginApplyNowOptions contains the optional parameters for the MaintenanceEventsClient.BeginApplyNow
//     method.
func (client *MaintenanceEventsClient) BeginApplyNow(ctx context.Context, resourceGroupName string, serverName string, maintenanceEventID string, options *MaintenanceEventsClientBeginApplyNowOptions) (*runtime.Poller[MaintenanceEventsClientApplyNowResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.applyNow(ctx, resourceGroupName, serverName, maintenanceEventID, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[MaintenanceEventsClientApplyNowResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[MaintenanceEventsClientApplyNowResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// ApplyNow - Applies the maintenance event immediately.
// If the operation fails it returns an *azcore.ResponseError type.
func (client *MaintenanceEventsClient) applyNow(ctx context.Context, resourceGroupName string, serverName string, maintenanceEventID string, options *MaintenanceEventsClientBeginApplyNowOptions) (*http.Response, error) {
	var err error
	const operationName = "MaintenanceEventsClient.BeginApplyNow"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.applyNowCreateRequest(ctx, resourceGroupName, serverName, maintenanceEventID, 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.StatusAccepted) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// applyNowCreateRequest creates the ApplyNow request.
func (client *MaintenanceEventsClient) applyNowCreateRequest(ctx context.Context, resourceGroupName string, serverName string, maintenanceEventID string, _ *MaintenanceEventsClientBeginApplyNowOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/maintenanceEvents/{maintenanceEventId}/applyNow"
	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 serverName == "" {
		return nil, errors.New("parameter serverName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serverName}", url.PathEscape(serverName))
	if maintenanceEventID == "" {
		return nil, errors.New("parameter maintenanceEventID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{maintenanceEventId}", url.PathEscape(maintenanceEventID))
	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", version20260401Preview)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Gets information about a maintenance event for a flexible server.
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - serverName - The name of the server.
//   - maintenanceEventID - The name of the MaintenanceEventResource
//   - options - MaintenanceEventsClientGetOptions contains the optional parameters for the MaintenanceEventsClient.Get method.
func (client *MaintenanceEventsClient) Get(ctx context.Context, resourceGroupName string, serverName string, maintenanceEventID string, options *MaintenanceEventsClientGetOptions) (MaintenanceEventsClientGetResponse, error) {
	var err error
	const operationName = "MaintenanceEventsClient.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, serverName, maintenanceEventID, options)
	if err != nil {
		return MaintenanceEventsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return MaintenanceEventsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return MaintenanceEventsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *MaintenanceEventsClient) getCreateRequest(ctx context.Context, resourceGroupName string, serverName string, maintenanceEventID string, _ *MaintenanceEventsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/maintenanceEvents/{maintenanceEventId}"
	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 serverName == "" {
		return nil, errors.New("parameter serverName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serverName}", url.PathEscape(serverName))
	if maintenanceEventID == "" {
		return nil, errors.New("parameter maintenanceEventID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{maintenanceEventId}", url.PathEscape(maintenanceEventID))
	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", version20260401Preview)
	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 *MaintenanceEventsClient) getHandleResponse(resp *http.Response) (MaintenanceEventsClientGetResponse, error) {
	result := MaintenanceEventsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.MaintenanceEventResource); err != nil {
		return MaintenanceEventsClientGetResponse{}, err
	}
	return result, nil
}

// NewListPager - Lists all maintenance events for a flexible server.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - serverName - The name of the server.
//   - options - MaintenanceEventsClientListOptions contains the optional parameters for the MaintenanceEventsClient.NewListPager
//     method.
func (client *MaintenanceEventsClient) NewListPager(resourceGroupName string, serverName string, options *MaintenanceEventsClientListOptions) *runtime.Pager[MaintenanceEventsClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[MaintenanceEventsClientListResponse]{
		More: func(page MaintenanceEventsClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *MaintenanceEventsClientListResponse) (MaintenanceEventsClientListResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "MaintenanceEventsClient.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, serverName, options)
			}, nil)
			if err != nil {
				return MaintenanceEventsClientListResponse{}, err
			}
			return client.listHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listCreateRequest creates the List request.
func (client *MaintenanceEventsClient) listCreateRequest(ctx context.Context, resourceGroupName string, serverName string, options *MaintenanceEventsClientListOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/maintenanceEvents"
	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 serverName == "" {
		return nil, errors.New("parameter serverName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serverName}", url.PathEscape(serverName))
	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", version20260401Preview)
	if options != nil && options.MaintenanceStatus != nil {
		reqQP.Set("maintenanceStatus", string(*options.MaintenanceStatus))
	}
	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 *MaintenanceEventsClient) listHandleResponse(resp *http.Response) (MaintenanceEventsClientListResponse, error) {
	result := MaintenanceEventsClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.MaintenanceEventResourceListResult); err != nil {
		return MaintenanceEventsClientListResponse{}, err
	}
	return result, nil
}

// BeginReschedule - Reschedules a maintenance event to a new date and time.
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - serverName - The name of the server.
//   - maintenanceEventID - The name of the MaintenanceEventResource
//   - body - The content of the action request
//   - options - MaintenanceEventsClientBeginRescheduleOptions contains the optional parameters for the MaintenanceEventsClient.BeginReschedule
//     method.
func (client *MaintenanceEventsClient) BeginReschedule(ctx context.Context, resourceGroupName string, serverName string, maintenanceEventID string, body MaintenanceEventRescheduleRequest, options *MaintenanceEventsClientBeginRescheduleOptions) (*runtime.Poller[MaintenanceEventsClientRescheduleResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.reschedule(ctx, resourceGroupName, serverName, maintenanceEventID, body, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[MaintenanceEventsClientRescheduleResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[MaintenanceEventsClientRescheduleResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Reschedule - Reschedules a maintenance event to a new date and time.
// If the operation fails it returns an *azcore.ResponseError type.
func (client *MaintenanceEventsClient) reschedule(ctx context.Context, resourceGroupName string, serverName string, maintenanceEventID string, body MaintenanceEventRescheduleRequest, options *MaintenanceEventsClientBeginRescheduleOptions) (*http.Response, error) {
	var err error
	const operationName = "MaintenanceEventsClient.BeginReschedule"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.rescheduleCreateRequest(ctx, resourceGroupName, serverName, maintenanceEventID, body, 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.StatusAccepted) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// rescheduleCreateRequest creates the Reschedule request.
func (client *MaintenanceEventsClient) rescheduleCreateRequest(ctx context.Context, resourceGroupName string, serverName string, maintenanceEventID string, body MaintenanceEventRescheduleRequest, _ *MaintenanceEventsClientBeginRescheduleOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/maintenanceEvents/{maintenanceEventId}/reschedule"
	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 serverName == "" {
		return nil, errors.New("parameter serverName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serverName}", url.PathEscape(serverName))
	if maintenanceEventID == "" {
		return nil, errors.New("parameter maintenanceEventID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{maintenanceEventId}", url.PathEscape(maintenanceEventID))
	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", version20260401Preview)
	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
}
