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

package synapse_test

import (
	"context"
	"fmt"
	"testing"

	"github.com/Azure/azure-sdk-for-go/services/preview/synapse/mgmt/v2.0/synapse" // nolint: staticcheck
	"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/synapse/parse"
	"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
	"github.com/hashicorp/terraform-provider-azurerm/utils"
)

type SynapseSqlPoolVulnerabilityAssessmentBaselineResource struct{}

func TestAccSynapseSqlPoolVulnerabilityAssessmentBaseline_basic(t *testing.T) {
	data := acceptance.BuildTestData(t, "azurerm_synapse_sql_pool_vulnerability_assessment_baseline", "test")
	r := SynapseSqlPoolVulnerabilityAssessmentBaselineResource{}

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

func TestAccSynapseSqlPoolVulnerabilityAssessmentBaseline_requiresImport(t *testing.T) {
	data := acceptance.BuildTestData(t, "azurerm_synapse_sql_pool_vulnerability_assessment_baseline", "test")
	r := SynapseSqlPoolVulnerabilityAssessmentBaselineResource{}

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

func TestAccSynapseSqlPoolVulnerabilityAssessmentBaseline_complete(t *testing.T) {
	data := acceptance.BuildTestData(t, "azurerm_synapse_sql_pool_vulnerability_assessment_baseline", "test")
	r := SynapseSqlPoolVulnerabilityAssessmentBaselineResource{}

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

func TestAccSynapseSqlPoolVulnerabilityAssessmentBaseline_update(t *testing.T) {
	data := acceptance.BuildTestData(t, "azurerm_synapse_sql_pool_vulnerability_assessment_baseline", "test")
	r := SynapseSqlPoolVulnerabilityAssessmentBaselineResource{}

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

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

	resp, err := client.Synapse.SQLPoolVulnerabilityAssessmentRuleBaselinesClient.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.SqlPoolName, id.RuleName, synapse.VulnerabilityAssessmentPolicyBaselineName(id.BaselineName))
	if err != nil {
		if utils.ResponseWasNotFound(resp.Response) {
			return utils.Bool(false), nil
		}
		return nil, fmt.Errorf("retrieving %s: %+v", id, err)
	}

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

func (r SynapseSqlPoolVulnerabilityAssessmentBaselineResource) basic(data acceptance.TestData) string {
	return fmt.Sprintf(`
%s

resource "azurerm_synapse_sql_pool_vulnerability_assessment_baseline" "test" {
  name                                 = "%s"
  rule_name                            = "VA1017"
  sql_pool_vulnerability_assessment_id = azurerm_synapse_sql_pool_vulnerability_assessment.test.id
}
`, r.template(data), data.RandomString)
}

func (r SynapseSqlPoolVulnerabilityAssessmentBaselineResource) requiresImport(data acceptance.TestData) string {
	return fmt.Sprintf(`
%s

resource "azurerm_synapse_sql_pool_vulnerability_assessment_baseline" "import" {
  name                                 = azurerm_synapse_sql_pool_vulnerability_assessment_baseline.test.name
  rule_name                            = azurerm_synapse_sql_pool_vulnerability_assessment_baseline.test.rule_name
  sql_pool_vulnerability_assessment_id = azurerm_synapse_sql_pool_vulnerability_assessment_baseline.test.sql_pool_vulnerability_assessment_id
}
`, r.basic(data))
}

func (r SynapseSqlPoolVulnerabilityAssessmentBaselineResource) complete(data acceptance.TestData) string {
	return fmt.Sprintf(`
%s

resource "azurerm_synapse_sql_pool_vulnerability_assessment_baseline" "test" {
  name                                 = "%s"
  rule_name                            = "VA1017"
  sql_pool_vulnerability_assessment_id = azurerm_synapse_sql_pool_vulnerability_assessment.test.id
  baseline {
    result = ["userA", "SELECT"]
  }
  baseline {
    result = ["userB", "SELECT"]
  }
}
`, r.template(data), data.RandomString)
}

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

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

resource "azurerm_storage_account" "sw" {
  name                     = "acctestsa%[3]ssw"
  resource_group_name      = azurerm_resource_group.test.name
  location                 = azurerm_resource_group.test.location
  account_kind             = "BlobStorage"
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

resource "azurerm_storage_data_lake_gen2_filesystem" "test" {
  name               = "acctest-%[1]d"
  storage_account_id = azurerm_storage_account.sw.id
}

resource "azurerm_synapse_workspace" "test" {
  name                                 = "acctestsw%[1]d"
  resource_group_name                  = azurerm_resource_group.test.name
  location                             = azurerm_resource_group.test.location
  storage_data_lake_gen2_filesystem_id = azurerm_storage_data_lake_gen2_filesystem.test.id
  sql_administrator_login              = "sqladminuser"
  sql_administrator_login_password     = "H@Sh1CoR3!"
  identity {
    type = "SystemAssigned"
  }
}

resource "azurerm_synapse_sql_pool" "test" {
  name                 = "acctestsp%[3]s"
  synapse_workspace_id = azurerm_synapse_workspace.test.id
  sku_name             = "DW100c"
  create_mode          = "Default"
  storage_account_type = "GRS"
}

resource "azurerm_storage_account" "test" {
  name                     = "acctestsa%[3]s"
  resource_group_name      = azurerm_resource_group.test.name
  location                 = azurerm_resource_group.test.location
  account_kind             = "BlobStorage"
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

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

resource "azurerm_synapse_sql_pool_security_alert_policy" "test" {
  sql_pool_id                = azurerm_synapse_sql_pool.test.id
  policy_state               = "Enabled"
  storage_endpoint           = azurerm_storage_account.test.primary_blob_endpoint
  storage_account_access_key = azurerm_storage_account.test.primary_access_key
}

resource "azurerm_synapse_sql_pool_vulnerability_assessment" "test" {
  sql_pool_security_alert_policy_id = azurerm_synapse_sql_pool_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
}
`, data.RandomInteger, data.Locations.Primary, data.RandomString)
}
