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

// AdministratorsMicrosoftEntraClient contains the methods for the AdministratorsMicrosoftEntra group.
// Don't use this type directly, use NewAdministratorsMicrosoftEntraClient() instead.
//
// Generated from API version 2026-04-01-preview
type AdministratorsMicrosoftEntraClient struct {
	internal       *arm.Client
	subscriptionID string
}

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

// BeginCreateOrUpdate - Creates a new server administrator associated to a Microsoft Entra principal.
// 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.
//   - objectID - Object identifier of the Microsoft Entra principal.
//   - parameters - Required parameters for adding a server administrator associated to a Microsoft Entra principal.
//   - options - AdministratorsMicrosoftEntraClientBeginCreateOrUpdateOptions contains the optional parameters for the AdministratorsMicrosoftEntraClient.BeginCreateOrUpdate
//     method.
func (client *AdministratorsMicrosoftEntraClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, serverName string, objectID string, parameters AdministratorMicrosoftEntraAdd, options *AdministratorsMicrosoftEntraClientBeginCreateOrUpdateOptions) (*runtime.Poller[AdministratorsMicrosoftEntraClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceGroupName, serverName, objectID, parameters, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AdministratorsMicrosoftEntraClientCreateOrUpdateResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AdministratorsMicrosoftEntraClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Creates a new server administrator associated to a Microsoft Entra principal.
// If the operation fails it returns an *azcore.ResponseError type.
func (client *AdministratorsMicrosoftEntraClient) createOrUpdate(ctx context.Context, resourceGroupName string, serverName string, objectID string, parameters AdministratorMicrosoftEntraAdd, options *AdministratorsMicrosoftEntraClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "AdministratorsMicrosoftEntraClient.BeginCreateOrUpdate"
	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, serverName, objectID, parameters, 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) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *AdministratorsMicrosoftEntraClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serverName string, objectID string, parameters AdministratorMicrosoftEntraAdd, _ *AdministratorsMicrosoftEntraClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}"
	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 objectID == "" {
		return nil, errors.New("parameter objectID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{objectId}", url.PathEscape(objectID))
	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", version20260401Preview)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Content-Type"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, parameters); err != nil {
		return nil, err
	}
	return req, nil
}

// BeginDelete - Deletes an existing server administrator associated to a Microsoft Entra principal.
// 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.
//   - objectID - Object identifier of the Microsoft Entra principal.
//   - options - AdministratorsMicrosoftEntraClientBeginDeleteOptions contains the optional parameters for the AdministratorsMicrosoftEntraClient.BeginDelete
//     method.
func (client *AdministratorsMicrosoftEntraClient) BeginDelete(ctx context.Context, resourceGroupName string, serverName string, objectID string, options *AdministratorsMicrosoftEntraClientBeginDeleteOptions) (*runtime.Poller[AdministratorsMicrosoftEntraClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, serverName, objectID, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AdministratorsMicrosoftEntraClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AdministratorsMicrosoftEntraClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Deletes an existing server administrator associated to a Microsoft Entra principal.
// If the operation fails it returns an *azcore.ResponseError type.
func (client *AdministratorsMicrosoftEntraClient) deleteOperation(ctx context.Context, resourceGroupName string, serverName string, objectID string, options *AdministratorsMicrosoftEntraClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "AdministratorsMicrosoftEntraClient.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, resourceGroupName, serverName, objectID, 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 *AdministratorsMicrosoftEntraClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serverName string, objectID string, _ *AdministratorsMicrosoftEntraClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}"
	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 objectID == "" {
		return nil, errors.New("parameter objectID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{objectId}", url.PathEscape(objectID))
	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", version20260401Preview)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	return req, nil
}

// Get - Gets information about a server administrator associated to a Microsoft Entra principal.
// 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.
//   - objectID - Object identifier of the Microsoft Entra principal.
//   - options - AdministratorsMicrosoftEntraClientGetOptions contains the optional parameters for the AdministratorsMicrosoftEntraClient.Get
//     method.
func (client *AdministratorsMicrosoftEntraClient) Get(ctx context.Context, resourceGroupName string, serverName string, objectID string, options *AdministratorsMicrosoftEntraClientGetOptions) (AdministratorsMicrosoftEntraClientGetResponse, error) {
	var err error
	const operationName = "AdministratorsMicrosoftEntraClient.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, objectID, options)
	if err != nil {
		return AdministratorsMicrosoftEntraClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return AdministratorsMicrosoftEntraClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return AdministratorsMicrosoftEntraClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

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

// NewListByServerPager - List all server administrators associated to a Microsoft Entra principal.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - serverName - The name of the server.
//   - options - AdministratorsMicrosoftEntraClientListByServerOptions contains the optional parameters for the AdministratorsMicrosoftEntraClient.NewListByServerPager
//     method.
func (client *AdministratorsMicrosoftEntraClient) NewListByServerPager(resourceGroupName string, serverName string, options *AdministratorsMicrosoftEntraClientListByServerOptions) *runtime.Pager[AdministratorsMicrosoftEntraClientListByServerResponse] {
	return runtime.NewPager(runtime.PagingHandler[AdministratorsMicrosoftEntraClientListByServerResponse]{
		More: func(page AdministratorsMicrosoftEntraClientListByServerResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *AdministratorsMicrosoftEntraClientListByServerResponse) (AdministratorsMicrosoftEntraClientListByServerResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AdministratorsMicrosoftEntraClient.NewListByServerPager")
			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.listByServerCreateRequest(ctx, resourceGroupName, serverName, options)
			}, nil)
			if err != nil {
				return AdministratorsMicrosoftEntraClientListByServerResponse{}, err
			}
			return client.listByServerHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByServerCreateRequest creates the ListByServer request.
func (client *AdministratorsMicrosoftEntraClient) listByServerCreateRequest(ctx context.Context, resourceGroupName string, serverName string, _ *AdministratorsMicrosoftEntraClientListByServerOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators"
	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)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByServerHandleResponse handles the ListByServer response.
func (client *AdministratorsMicrosoftEntraClient) listByServerHandleResponse(resp *http.Response) (AdministratorsMicrosoftEntraClientListByServerResponse, error) {
	result := AdministratorsMicrosoftEntraClientListByServerResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.AdministratorMicrosoftEntraList); err != nil {
		return AdministratorsMicrosoftEntraClientListByServerResponse{}, err
	}
	return result, nil
}
