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

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

// DbSystemsClient contains the methods for the DbSystems group.
// Don't use this type directly, use NewDbSystemsClient() instead.
//
// Generated from API version 2025-09-01
type DbSystemsClient struct {
	internal       *arm.Client
	subscriptionID string
}

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

// BeginCreateOrUpdate - Create a DbSystem
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - dbSystemName - The name of the DbSystem
//   - resource - Resource create parameters.
//   - options - DbSystemsClientBeginCreateOrUpdateOptions contains the optional parameters for the DbSystemsClient.BeginCreateOrUpdate
//     method.
func (client *DbSystemsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, dbSystemName string, resource DbSystem, options *DbSystemsClientBeginCreateOrUpdateOptions) (*runtime.Poller[DbSystemsClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceGroupName, dbSystemName, resource, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DbSystemsClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DbSystemsClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Create a DbSystem
// If the operation fails it returns an *azcore.ResponseError type.
func (client *DbSystemsClient) createOrUpdate(ctx context.Context, resourceGroupName string, dbSystemName string, resource DbSystem, options *DbSystemsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "DbSystemsClient.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, dbSystemName, 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
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *DbSystemsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, dbSystemName string, resource DbSystem, _ *DbSystemsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/dbSystems/{dbSystemName}"
	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 dbSystemName == "" {
		return nil, errors.New("parameter dbSystemName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dbSystemName}", url.PathEscape(dbSystemName))
	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", version20250901)
	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 - Delete a DbSystem
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - dbSystemName - The name of the DbSystem
//   - options - DbSystemsClientBeginDeleteOptions contains the optional parameters for the DbSystemsClient.BeginDelete method.
func (client *DbSystemsClient) BeginDelete(ctx context.Context, resourceGroupName string, dbSystemName string, options *DbSystemsClientBeginDeleteOptions) (*runtime.Poller[DbSystemsClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, dbSystemName, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DbSystemsClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DbSystemsClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Delete a DbSystem
// If the operation fails it returns an *azcore.ResponseError type.
func (client *DbSystemsClient) deleteOperation(ctx context.Context, resourceGroupName string, dbSystemName string, options *DbSystemsClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "DbSystemsClient.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, dbSystemName, 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 *DbSystemsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, dbSystemName string, _ *DbSystemsClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/dbSystems/{dbSystemName}"
	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 dbSystemName == "" {
		return nil, errors.New("parameter dbSystemName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dbSystemName}", url.PathEscape(dbSystemName))
	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", version20250901)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	return req, nil
}

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

// getCreateRequest creates the Get request.
func (client *DbSystemsClient) getCreateRequest(ctx context.Context, resourceGroupName string, dbSystemName string, _ *DbSystemsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/dbSystems/{dbSystemName}"
	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 dbSystemName == "" {
		return nil, errors.New("parameter dbSystemName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dbSystemName}", url.PathEscape(dbSystemName))
	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", version20250901)
	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 *DbSystemsClient) getHandleResponse(resp *http.Response) (DbSystemsClientGetResponse, error) {
	result := DbSystemsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.DbSystem); err != nil {
		return DbSystemsClientGetResponse{}, err
	}
	return result, nil
}

// NewListByResourceGroupPager - List DbSystem resources by resource group
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - options - DbSystemsClientListByResourceGroupOptions contains the optional parameters for the DbSystemsClient.NewListByResourceGroupPager
//     method.
func (client *DbSystemsClient) NewListByResourceGroupPager(resourceGroupName string, options *DbSystemsClientListByResourceGroupOptions) *runtime.Pager[DbSystemsClientListByResourceGroupResponse] {
	return runtime.NewPager(runtime.PagingHandler[DbSystemsClientListByResourceGroupResponse]{
		More: func(page DbSystemsClientListByResourceGroupResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *DbSystemsClientListByResourceGroupResponse) (DbSystemsClientListByResourceGroupResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DbSystemsClient.NewListByResourceGroupPager")
			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.listByResourceGroupCreateRequest(ctx, resourceGroupName, options)
			}, nil)
			if err != nil {
				return DbSystemsClientListByResourceGroupResponse{}, err
			}
			return client.listByResourceGroupHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *DbSystemsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *DbSystemsClientListByResourceGroupOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/dbSystems"
	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", version20250901)
	req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *DbSystemsClient) listByResourceGroupHandleResponse(resp *http.Response) (DbSystemsClientListByResourceGroupResponse, error) {
	result := DbSystemsClientListByResourceGroupResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.DbSystemListResult); err != nil {
		return DbSystemsClientListByResourceGroupResponse{}, err
	}
	return result, nil
}

// NewListBySubscriptionPager - List DbSystem resources by subscription ID
//   - options - DbSystemsClientListBySubscriptionOptions contains the optional parameters for the DbSystemsClient.NewListBySubscriptionPager
//     method.
func (client *DbSystemsClient) NewListBySubscriptionPager(options *DbSystemsClientListBySubscriptionOptions) *runtime.Pager[DbSystemsClientListBySubscriptionResponse] {
	return runtime.NewPager(runtime.PagingHandler[DbSystemsClientListBySubscriptionResponse]{
		More: func(page DbSystemsClientListBySubscriptionResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *DbSystemsClientListBySubscriptionResponse) (DbSystemsClientListBySubscriptionResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DbSystemsClient.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 DbSystemsClientListBySubscriptionResponse{}, err
			}
			return client.listBySubscriptionHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listBySubscriptionCreateRequest creates the ListBySubscription request.
func (client *DbSystemsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *DbSystemsClientListBySubscriptionOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/dbSystems"
	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", version20250901)
	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 *DbSystemsClient) listBySubscriptionHandleResponse(resp *http.Response) (DbSystemsClientListBySubscriptionResponse, error) {
	result := DbSystemsClientListBySubscriptionResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.DbSystemListResult); err != nil {
		return DbSystemsClientListBySubscriptionResponse{}, err
	}
	return result, nil
}

// BeginUpdate - Update a DbSystem
// If the operation fails it returns an *azcore.ResponseError type.
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - dbSystemName - The name of the DbSystem
//   - properties - The resource properties to be updated.
//   - options - DbSystemsClientBeginUpdateOptions contains the optional parameters for the DbSystemsClient.BeginUpdate method.
func (client *DbSystemsClient) BeginUpdate(ctx context.Context, resourceGroupName string, dbSystemName string, properties DbSystemUpdate, options *DbSystemsClientBeginUpdateOptions) (*runtime.Poller[DbSystemsClientUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.update(ctx, resourceGroupName, dbSystemName, properties, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DbSystemsClientUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DbSystemsClientUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Update - Update a DbSystem
// If the operation fails it returns an *azcore.ResponseError type.
func (client *DbSystemsClient) update(ctx context.Context, resourceGroupName string, dbSystemName string, properties DbSystemUpdate, options *DbSystemsClientBeginUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "DbSystemsClient.BeginUpdate"
	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, dbSystemName, properties, 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
}

// updateCreateRequest creates the Update request.
func (client *DbSystemsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, dbSystemName string, properties DbSystemUpdate, _ *DbSystemsClientBeginUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/dbSystems/{dbSystemName}"
	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 dbSystemName == "" {
		return nil, errors.New("parameter dbSystemName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dbSystemName}", url.PathEscape(dbSystemName))
	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", version20250901)
	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
}
