// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package mssql_test

import (
	"context"
	"fmt"
	"testing"

	"github.com/hashicorp/go-azure-helpers/lang/pointer"
	"github.com/hashicorp/go-azure-helpers/lang/response"
	"github.com/hashicorp/go-azure-helpers/resourcemanager/commonids"
	"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance"
	"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check"
	"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
	"github.com/hashicorp/terraform-provider-azurerm/internal/services/mssql/parse"
	"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
)

type MsSqlServerVulnerabilityAssessmentResource struct{}

func TestAccAzureRMMssqlServerVulnerabilityAssessment_basic(t *testing.T) {
	data := acceptance.BuildTestData(t, "azurerm_mssql_server_vulnerability_assessment", "test")
	r := MsSqlServerVulnerabilityAssessmentResource{}

	data.ResourceTest(t, r, []acceptance.TestStep{
		{
			Config: r.basic(data),
			Check: acceptance.ComposeTestCheckFunc(
				check.That(data.ResourceName).ExistsInAzure(r),
			),
		},
		data.ImportStep("storage_account_access_key"),
	})
}

func TestAccAzureRMMssqlServerVulnerabilityAssessment_update(t *testing.T) {
	data := acceptance.BuildTestData(t, "azurerm_mssql_server_vulnerability_assessment", "test")
	r := MsSqlServerVulnerabilityAssessmentResource{}

	data.ResourceTest(t, r, []acceptance.TestStep{
		{
			Config: r.basic(data),
			Check: acceptance.ComposeTestCheckFunc(
				check.That(data.ResourceName).ExistsInAzure(r),
			),
		},
		data.ImportStep("storage_account_access_key"),
		{
			Config: r.update(data),
			Check: acceptance.ComposeTestCheckFunc(
				check.That(data.ResourceName).ExistsInAzure(r),
			),
		},
		data.ImportStep("storage_account_access_key"),
	})
}

func (MsSqlServerVulnerabilityAssessmentResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
	id, err := parse.ServerVulnerabilityAssessmentID(state.ID)
	if err != nil {
		return nil, err
	}

	serverId := commonids.NewSqlServerID(id.SubscriptionId, id.ResourceGroup, id.ServerName)

	resp, err := client.MSSQL.ServerVulnerabilityAssessmentsClient.Get(ctx, serverId)
	if err != nil {
		if response.WasNotFound(resp.HttpResponse) {
			return nil, fmt.Errorf("%s does not exist", id)
		}

		return nil, fmt.Errorf("reading %s: %v", id, err)
	}

	return pointer.To(resp.Model != nil), nil
}

func (r MsSqlServerVulnerabilityAssessmentResource) basic(data acceptance.TestData) string {
	return fmt.Sprintf(`
%[1]s

resource "azurerm_mssql_server_vulnerability_assessment" "test" {
  server_security_alert_policy_id = azurerm_mssql_server_security_alert_policy.test.id
  storage_container_path          = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/"
  storage_account_access_key      = azurerm_storage_account.test.primary_access_key
}
`, r.server(data))
}

func (r MsSqlServerVulnerabilityAssessmentResource) update(data acceptance.TestData) string {
	return fmt.Sprintf(`
%[1]s

resource "azurerm_mssql_server_vulnerability_assessment" "test" {
  server_security_alert_policy_id = azurerm_mssql_server_security_alert_policy.test.id
  storage_container_path          = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/"
  storage_account_access_key      = azurerm_storage_account.test.primary_access_key

  recurring_scans {
    enabled                   = true
    email_subscription_admins = true
    emails = [
      "email@example1.com",
      "email@example2.com"
    ]
  }
}
`, r.server(data))
}

func (MsSqlServerVulnerabilityAssessmentResource) server(data acceptance.TestData) string {
	return fmt.Sprintf(`
provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "test" {
  name     = "acctestRG-mssql-%[1]d"
  location = "%[2]s"
}

resource "azurerm_mssql_server" "test" {
  name                         = "acctestsqlserver%[1]d"
  resource_group_name          = azurerm_resource_group.test.name
  location                     = azurerm_resource_group.test.location
  version                      = "12.0"
  administrator_login          = "mradministrator"
  administrator_login_password = "thisIsDog11"
}

resource "azurerm_storage_account" "test" {
  name                     = "accsa%[1]d"
  resource_group_name      = azurerm_resource_group.test.name
  location                 = "%[2]s"
  account_tier             = "Standard"
  account_replication_type = "GRS"
}

resource "azurerm_storage_container" "test" {
  name                  = "acctestsc%[1]d"
  storage_account_name  = azurerm_storage_account.test.name
  container_access_type = "private"
}

resource "azurerm_mssql_server_security_alert_policy" "test" {
  resource_group_name = azurerm_resource_group.test.name
  server_name         = azurerm_mssql_server.test.name
  state               = "Enabled"
}
`, data.RandomInteger, data.Locations.Primary)
}
