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

package mssqlmanagedinstance_test

import (
	"context"
	"fmt"
	"testing"

	"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/mssqlmanagedinstance/parse"
	"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
	"github.com/hashicorp/terraform-provider-azurerm/utils"
)

type MsSqlManagedInstanceVulnerabilityAssessmentResource struct{}

func TestAccAzureRMMssqlManagedInstanceVulnerabilityAssessment_basic(t *testing.T) {
	data := acceptance.BuildTestData(t, "azurerm_mssql_managed_instance_vulnerability_assessment", "test")
	r := MsSqlManagedInstanceVulnerabilityAssessmentResource{}

	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 TestAccAzureRMMssqlManagedInstanceVulnerabilityAssessment_update(t *testing.T) {
	data := acceptance.BuildTestData(t, "azurerm_mssql_managed_instance_vulnerability_assessment", "test")
	r := MsSqlManagedInstanceVulnerabilityAssessmentResource{}

	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 (MsSqlManagedInstanceVulnerabilityAssessmentResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
	id, err := parse.ManagedInstanceVulnerabilityAssessmentID(state.ID)
	if err != nil {
		return nil, err
	}

	instanceId := commonids.NewSqlManagedInstanceID(id.SubscriptionId, id.ResourceGroup, id.ManagedInstanceName)

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

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

	return utils.Bool(resp.Model != nil), nil
}

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

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

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

resource "azurerm_mssql_managed_instance_security_alert_policy" "test" {
  resource_group_name        = azurerm_resource_group.test.name
  managed_instance_name      = azurerm_mssql_managed_instance.test.name
  enabled                    = true
  storage_endpoint           = azurerm_storage_account.test.primary_blob_endpoint
  storage_account_access_key = azurerm_storage_account.test.primary_access_key
  retention_days             = 30
}

resource "azurerm_mssql_managed_instance_vulnerability_assessment" "test" {
  managed_instance_id        = azurerm_mssql_managed_instance.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

  depends_on = [azurerm_mssql_managed_instance_security_alert_policy.test]
}
`, MsSqlManagedInstanceResource{}.basic(data), data.RandomInteger, data.Locations.Primary)
}

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

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

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

resource "azurerm_mssql_managed_instance_security_alert_policy" "test" {
  resource_group_name        = azurerm_resource_group.test.name
  managed_instance_name      = azurerm_mssql_managed_instance.test.name
  enabled                    = true
  storage_endpoint           = azurerm_storage_account.test.primary_blob_endpoint
  storage_account_access_key = azurerm_storage_account.test.primary_access_key
  retention_days             = 30
}

resource "azurerm_mssql_managed_instance_vulnerability_assessment" "test" {
  managed_instance_id        = azurerm_mssql_managed_instance.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"
    ]
  }

  depends_on = [azurerm_mssql_managed_instance_security_alert_policy.test]
}
`, MsSqlManagedInstanceResource{}.basic(data), data.RandomInteger, data.Locations.Primary)
}
