package sql

// 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.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"github.com/Azure/go-autorest/autorest/validation"
	"github.com/Azure/go-autorest/tracing"
	"net/http"
)

// VulnerabilityAssessmentRuleBaselineClient is the the Azure SQL Database management API provides a RESTful set of web
// services that interact with Azure SQL Database services to manage your databases. The API enables you to create,
// retrieve, update, and delete databases.
type VulnerabilityAssessmentRuleBaselineClient struct {
	BaseClient
}

// NewVulnerabilityAssessmentRuleBaselineClient creates an instance of the VulnerabilityAssessmentRuleBaselineClient
// client.
func NewVulnerabilityAssessmentRuleBaselineClient(subscriptionID string) VulnerabilityAssessmentRuleBaselineClient {
	return NewVulnerabilityAssessmentRuleBaselineClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewVulnerabilityAssessmentRuleBaselineClientWithBaseURI creates an instance of the
// VulnerabilityAssessmentRuleBaselineClient client using a custom endpoint.  Use this when interacting with an Azure
// cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewVulnerabilityAssessmentRuleBaselineClientWithBaseURI(baseURI string, subscriptionID string) VulnerabilityAssessmentRuleBaselineClient {
	return VulnerabilityAssessmentRuleBaselineClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// CreateOrUpdate creates or updates a database's vulnerability assessment rule baseline.
// Parameters:
// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value
// from the Azure Resource Manager API or the portal.
// serverName - the name of the server.
// ruleID - the vulnerability assessment rule ID.
// parameters - the requested rule baseline resource.
func (client VulnerabilityAssessmentRuleBaselineClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serverName string, ruleID string, parameters DatabaseSQLVulnerabilityAssessmentRuleBaselineInput) (result DatabaseSQLVulnerabilityAssessmentRuleBaseline, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/VulnerabilityAssessmentRuleBaselineClient.CreateOrUpdate")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: parameters,
			Constraints: []validation.Constraint{{Target: "parameters.DatabaseSQLVulnerabilityAssessmentRuleBaselineInputProperties", Name: validation.Null, Rule: false,
				Chain: []validation.Constraint{{Target: "parameters.DatabaseSQLVulnerabilityAssessmentRuleBaselineInputProperties.LatestScan", Name: validation.Null, Rule: true, Chain: nil},
					{Target: "parameters.DatabaseSQLVulnerabilityAssessmentRuleBaselineInputProperties.Results", Name: validation.Null, Rule: true, Chain: nil},
				}}}}}); err != nil {
		return result, validation.NewError("sql.VulnerabilityAssessmentRuleBaselineClient", "CreateOrUpdate", err.Error())
	}

	req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serverName, ruleID, parameters)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.VulnerabilityAssessmentRuleBaselineClient", "CreateOrUpdate", nil, "Failure preparing request")
		return
	}

	resp, err := client.CreateOrUpdateSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "sql.VulnerabilityAssessmentRuleBaselineClient", "CreateOrUpdate", resp, "Failure sending request")
		return
	}

	result, err = client.CreateOrUpdateResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.VulnerabilityAssessmentRuleBaselineClient", "CreateOrUpdate", resp, "Failure responding to request")
		return
	}

	return
}

// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client VulnerabilityAssessmentRuleBaselineClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serverName string, ruleID string, parameters DatabaseSQLVulnerabilityAssessmentRuleBaselineInput) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"baselineName":                autorest.Encode("path", "default"),
		"resourceGroupName":           autorest.Encode("path", resourceGroupName),
		"ruleId":                      autorest.Encode("path", ruleID),
		"serverName":                  autorest.Encode("path", serverName),
		"subscriptionId":              autorest.Encode("path", client.SubscriptionID),
		"vulnerabilityAssessmentName": autorest.Encode("path", "default"),
	}

	const APIVersion = "2022-02-01-preview"
	queryParameters := map[string]interface{}{
		"api-version":        APIVersion,
		"systemDatabaseName": autorest.Encode("query", "master"),
	}

	parameters.SystemData = nil
	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPut(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/sqlVulnerabilityAssessments/{vulnerabilityAssessmentName}/baselines/{baselineName}/rules/{ruleId}", pathParameters),
		autorest.WithJSON(parameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client VulnerabilityAssessmentRuleBaselineClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}

// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client VulnerabilityAssessmentRuleBaselineClient) CreateOrUpdateResponder(resp *http.Response) (result DatabaseSQLVulnerabilityAssessmentRuleBaseline, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// Get gets a system database's sql vulnerability assessment rule baseline.
// Parameters:
// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value
// from the Azure Resource Manager API or the portal.
// serverName - the name of the server.
// ruleID - the vulnerability assessment rule ID.
func (client VulnerabilityAssessmentRuleBaselineClient) Get(ctx context.Context, resourceGroupName string, serverName string, ruleID string) (result DatabaseSQLVulnerabilityAssessmentRuleBaseline, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/VulnerabilityAssessmentRuleBaselineClient.Get")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.GetPreparer(ctx, resourceGroupName, serverName, ruleID)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.VulnerabilityAssessmentRuleBaselineClient", "Get", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "sql.VulnerabilityAssessmentRuleBaselineClient", "Get", resp, "Failure sending request")
		return
	}

	result, err = client.GetResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.VulnerabilityAssessmentRuleBaselineClient", "Get", resp, "Failure responding to request")
		return
	}

	return
}

// GetPreparer prepares the Get request.
func (client VulnerabilityAssessmentRuleBaselineClient) GetPreparer(ctx context.Context, resourceGroupName string, serverName string, ruleID string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"baselineName":                autorest.Encode("path", "default"),
		"resourceGroupName":           autorest.Encode("path", resourceGroupName),
		"ruleId":                      autorest.Encode("path", ruleID),
		"serverName":                  autorest.Encode("path", serverName),
		"subscriptionId":              autorest.Encode("path", client.SubscriptionID),
		"vulnerabilityAssessmentName": autorest.Encode("path", "default"),
	}

	const APIVersion = "2022-02-01-preview"
	queryParameters := map[string]interface{}{
		"api-version":        APIVersion,
		"systemDatabaseName": autorest.Encode("query", "master"),
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/sqlVulnerabilityAssessments/{vulnerabilityAssessmentName}/baselines/{baselineName}/rules/{ruleId}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client VulnerabilityAssessmentRuleBaselineClient) GetSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}

// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client VulnerabilityAssessmentRuleBaselineClient) GetResponder(resp *http.Response) (result DatabaseSQLVulnerabilityAssessmentRuleBaseline, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// ListByBaseline gets a system database's sql vulnerability assessment rule baseline.
// Parameters:
// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value
// from the Azure Resource Manager API or the portal.
// serverName - the name of the server.
func (client VulnerabilityAssessmentRuleBaselineClient) ListByBaseline(ctx context.Context, resourceGroupName string, serverName string) (result DatabaseSQLVulnerabilityAssessmentRuleBaselineListResultPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/VulnerabilityAssessmentRuleBaselineClient.ListByBaseline")
		defer func() {
			sc := -1
			if result.dsvarblr.Response.Response != nil {
				sc = result.dsvarblr.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.fn = client.listByBaselineNextResults
	req, err := client.ListByBaselinePreparer(ctx, resourceGroupName, serverName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.VulnerabilityAssessmentRuleBaselineClient", "ListByBaseline", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByBaselineSender(req)
	if err != nil {
		result.dsvarblr.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "sql.VulnerabilityAssessmentRuleBaselineClient", "ListByBaseline", resp, "Failure sending request")
		return
	}

	result.dsvarblr, err = client.ListByBaselineResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.VulnerabilityAssessmentRuleBaselineClient", "ListByBaseline", resp, "Failure responding to request")
		return
	}
	if result.dsvarblr.hasNextLink() && result.dsvarblr.IsEmpty() {
		err = result.NextWithContext(ctx)
		return
	}

	return
}

// ListByBaselinePreparer prepares the ListByBaseline request.
func (client VulnerabilityAssessmentRuleBaselineClient) ListByBaselinePreparer(ctx context.Context, resourceGroupName string, serverName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"baselineName":                autorest.Encode("path", "default"),
		"resourceGroupName":           autorest.Encode("path", resourceGroupName),
		"serverName":                  autorest.Encode("path", serverName),
		"subscriptionId":              autorest.Encode("path", client.SubscriptionID),
		"vulnerabilityAssessmentName": autorest.Encode("path", "default"),
	}

	const APIVersion = "2022-02-01-preview"
	queryParameters := map[string]interface{}{
		"api-version":        APIVersion,
		"systemDatabaseName": autorest.Encode("query", "master"),
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/sqlVulnerabilityAssessments/{vulnerabilityAssessmentName}/baselines/{baselineName}/rules", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListByBaselineSender sends the ListByBaseline request. The method will close the
// http.Response Body if it receives an error.
func (client VulnerabilityAssessmentRuleBaselineClient) ListByBaselineSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}

// ListByBaselineResponder handles the response to the ListByBaseline request. The method always
// closes the http.Response Body.
func (client VulnerabilityAssessmentRuleBaselineClient) ListByBaselineResponder(resp *http.Response) (result DatabaseSQLVulnerabilityAssessmentRuleBaselineListResult, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// listByBaselineNextResults retrieves the next set of results, if any.
func (client VulnerabilityAssessmentRuleBaselineClient) listByBaselineNextResults(ctx context.Context, lastResults DatabaseSQLVulnerabilityAssessmentRuleBaselineListResult) (result DatabaseSQLVulnerabilityAssessmentRuleBaselineListResult, err error) {
	req, err := lastResults.databaseSQLVulnerabilityAssessmentRuleBaselineListResultPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "sql.VulnerabilityAssessmentRuleBaselineClient", "listByBaselineNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListByBaselineSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "sql.VulnerabilityAssessmentRuleBaselineClient", "listByBaselineNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListByBaselineResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.VulnerabilityAssessmentRuleBaselineClient", "listByBaselineNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListByBaselineComplete enumerates all values, automatically crossing page boundaries as required.
func (client VulnerabilityAssessmentRuleBaselineClient) ListByBaselineComplete(ctx context.Context, resourceGroupName string, serverName string) (result DatabaseSQLVulnerabilityAssessmentRuleBaselineListResultIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/VulnerabilityAssessmentRuleBaselineClient.ListByBaseline")
		defer func() {
			sc := -1
			if result.Response().Response.Response != nil {
				sc = result.page.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.page, err = client.ListByBaseline(ctx, resourceGroupName, serverName)
	return
}
