// 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) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

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

// MigrationsClient contains the methods for the Migrations group.
// Don't use this type directly, use NewMigrationsClient() instead.
type MigrationsClient struct {
	internal *arm.Client
}

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

// Create - Creates a new migration.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-01-01-preview
//   - subscriptionID - The subscription ID of the target database server.
//   - resourceGroupName - The resource group name of the target database server.
//   - targetDbServerName - The name of the target database server.
//   - migrationName - The name of the migration.
//   - parameters - The required parameters for creating a migration.
//   - options - MigrationsClientCreateOptions contains the optional parameters for the MigrationsClient.Create method.
func (client *MigrationsClient) Create(ctx context.Context, subscriptionID string, resourceGroupName string, targetDbServerName string, migrationName string, parameters MigrationResource, options *MigrationsClientCreateOptions) (MigrationsClientCreateResponse, error) {
	var err error
	const operationName = "MigrationsClient.Create"
	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, subscriptionID, resourceGroupName, targetDbServerName, migrationName, parameters, options)
	if err != nil {
		return MigrationsClientCreateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return MigrationsClientCreateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return MigrationsClientCreateResponse{}, err
	}
	resp, err := client.createHandleResponse(httpResp)
	return resp, err
}

// createCreateRequest creates the Create request.
func (client *MigrationsClient) createCreateRequest(ctx context.Context, subscriptionID string, resourceGroupName string, targetDbServerName string, migrationName string, parameters MigrationResource, _ *MigrationsClientCreateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{targetDbServerName}/migrations/{migrationName}"
	if subscriptionID == "" {
		return nil, errors.New("parameter subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if targetDbServerName == "" {
		return nil, errors.New("parameter targetDbServerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{targetDbServerName}", url.PathEscape(targetDbServerName))
	if migrationName == "" {
		return nil, errors.New("parameter migrationName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{migrationName}", url.PathEscape(migrationName))
	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", "2025-01-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, parameters); err != nil {
		return nil, err
	}
	return req, nil
}

// createHandleResponse handles the Create response.
func (client *MigrationsClient) createHandleResponse(resp *http.Response) (MigrationsClientCreateResponse, error) {
	result := MigrationsClientCreateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.MigrationResource); err != nil {
		return MigrationsClientCreateResponse{}, err
	}
	return result, nil
}

// Delete - Deletes a migration.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-01-01-preview
//   - subscriptionID - The subscription ID of the target database server.
//   - resourceGroupName - The resource group name of the target database server.
//   - targetDbServerName - The name of the target database server.
//   - migrationName - The name of the migration.
//   - options - MigrationsClientDeleteOptions contains the optional parameters for the MigrationsClient.Delete method.
func (client *MigrationsClient) Delete(ctx context.Context, subscriptionID string, resourceGroupName string, targetDbServerName string, migrationName string, options *MigrationsClientDeleteOptions) (MigrationsClientDeleteResponse, error) {
	var err error
	const operationName = "MigrationsClient.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, subscriptionID, resourceGroupName, targetDbServerName, migrationName, options)
	if err != nil {
		return MigrationsClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return MigrationsClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return MigrationsClientDeleteResponse{}, err
	}
	return MigrationsClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *MigrationsClient) deleteCreateRequest(ctx context.Context, subscriptionID string, resourceGroupName string, targetDbServerName string, migrationName string, _ *MigrationsClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{targetDbServerName}/migrations/{migrationName}"
	if subscriptionID == "" {
		return nil, errors.New("parameter subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if targetDbServerName == "" {
		return nil, errors.New("parameter targetDbServerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{targetDbServerName}", url.PathEscape(targetDbServerName))
	if migrationName == "" {
		return nil, errors.New("parameter migrationName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{migrationName}", url.PathEscape(migrationName))
	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", "2025-01-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Gets details of a migration.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-01-01-preview
//   - subscriptionID - The subscription ID of the target database server.
//   - resourceGroupName - The resource group name of the target database server.
//   - targetDbServerName - The name of the target database server.
//   - migrationName - The name of the migration.
//   - options - MigrationsClientGetOptions contains the optional parameters for the MigrationsClient.Get method.
func (client *MigrationsClient) Get(ctx context.Context, subscriptionID string, resourceGroupName string, targetDbServerName string, migrationName string, options *MigrationsClientGetOptions) (MigrationsClientGetResponse, error) {
	var err error
	const operationName = "MigrationsClient.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, subscriptionID, resourceGroupName, targetDbServerName, migrationName, options)
	if err != nil {
		return MigrationsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return MigrationsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return MigrationsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *MigrationsClient) getCreateRequest(ctx context.Context, subscriptionID string, resourceGroupName string, targetDbServerName string, migrationName string, _ *MigrationsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{targetDbServerName}/migrations/{migrationName}"
	if subscriptionID == "" {
		return nil, errors.New("parameter subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if targetDbServerName == "" {
		return nil, errors.New("parameter targetDbServerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{targetDbServerName}", url.PathEscape(targetDbServerName))
	if migrationName == "" {
		return nil, errors.New("parameter migrationName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{migrationName}", url.PathEscape(migrationName))
	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", "2025-01-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListByTargetServerPager - List all the migrations on a given target server.
//
// Generated from API version 2025-01-01-preview
//   - subscriptionID - The subscription ID of the target database server.
//   - resourceGroupName - The resource group name of the target database server.
//   - targetDbServerName - The name of the target database server.
//   - options - MigrationsClientListByTargetServerOptions contains the optional parameters for the MigrationsClient.NewListByTargetServerPager
//     method.
func (client *MigrationsClient) NewListByTargetServerPager(subscriptionID string, resourceGroupName string, targetDbServerName string, options *MigrationsClientListByTargetServerOptions) *runtime.Pager[MigrationsClientListByTargetServerResponse] {
	return runtime.NewPager(runtime.PagingHandler[MigrationsClientListByTargetServerResponse]{
		More: func(page MigrationsClientListByTargetServerResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *MigrationsClientListByTargetServerResponse) (MigrationsClientListByTargetServerResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "MigrationsClient.NewListByTargetServerPager")
			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.listByTargetServerCreateRequest(ctx, subscriptionID, resourceGroupName, targetDbServerName, options)
			}, nil)
			if err != nil {
				return MigrationsClientListByTargetServerResponse{}, err
			}
			return client.listByTargetServerHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByTargetServerCreateRequest creates the ListByTargetServer request.
func (client *MigrationsClient) listByTargetServerCreateRequest(ctx context.Context, subscriptionID string, resourceGroupName string, targetDbServerName string, options *MigrationsClientListByTargetServerOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{targetDbServerName}/migrations"
	if subscriptionID == "" {
		return nil, errors.New("parameter subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if targetDbServerName == "" {
		return nil, errors.New("parameter targetDbServerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{targetDbServerName}", url.PathEscape(targetDbServerName))
	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", "2025-01-01-preview")
	if options != nil && options.MigrationListFilter != nil {
		reqQP.Set("migrationListFilter", string(*options.MigrationListFilter))
	}
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByTargetServerHandleResponse handles the ListByTargetServer response.
func (client *MigrationsClient) listByTargetServerHandleResponse(resp *http.Response) (MigrationsClientListByTargetServerResponse, error) {
	result := MigrationsClientListByTargetServerResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.MigrationResourceListResult); err != nil {
		return MigrationsClientListByTargetServerResponse{}, err
	}
	return result, nil
}

// Update - Updates an existing migration. The request body can contain one to many of the mutable properties present in the
// migration definition. Certain property updates initiate migration state transitions.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-01-01-preview
//   - subscriptionID - The subscription ID of the target database server.
//   - resourceGroupName - The resource group name of the target database server.
//   - targetDbServerName - The name of the target database server.
//   - migrationName - The name of the migration.
//   - parameters - The required parameters for updating a migration.
//   - options - MigrationsClientUpdateOptions contains the optional parameters for the MigrationsClient.Update method.
func (client *MigrationsClient) Update(ctx context.Context, subscriptionID string, resourceGroupName string, targetDbServerName string, migrationName string, parameters MigrationResourceForPatch, options *MigrationsClientUpdateOptions) (MigrationsClientUpdateResponse, error) {
	var err error
	const operationName = "MigrationsClient.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, subscriptionID, resourceGroupName, targetDbServerName, migrationName, parameters, options)
	if err != nil {
		return MigrationsClientUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return MigrationsClientUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return MigrationsClientUpdateResponse{}, err
	}
	resp, err := client.updateHandleResponse(httpResp)
	return resp, err
}

// updateCreateRequest creates the Update request.
func (client *MigrationsClient) updateCreateRequest(ctx context.Context, subscriptionID string, resourceGroupName string, targetDbServerName string, migrationName string, parameters MigrationResourceForPatch, _ *MigrationsClientUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{targetDbServerName}/migrations/{migrationName}"
	if subscriptionID == "" {
		return nil, errors.New("parameter subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if targetDbServerName == "" {
		return nil, errors.New("parameter targetDbServerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{targetDbServerName}", url.PathEscape(targetDbServerName))
	if migrationName == "" {
		return nil, errors.New("parameter migrationName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{migrationName}", url.PathEscape(migrationName))
	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", "2025-01-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, parameters); err != nil {
		return nil, err
	}
	return req, nil
}

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