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

package securitycenter_test

import (
	"context"
	"fmt"
	"testing"

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

type ServerVulnerabilityAssessmentResource struct{}

func testAccServerVulnerabilityAssessment_basic(t *testing.T) {
	data := acceptance.BuildTestData(t, "azurerm_security_center_server_vulnerability_assessment", "test")
	r := ServerVulnerabilityAssessmentResource{}

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

func testAccServerVulnerabilityAssessment_requiresImport(t *testing.T) {
	data := acceptance.BuildTestData(t, "azurerm_security_center_server_vulnerability_assessment", "test")
	r := ServerVulnerabilityAssessmentResource{}

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

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

	resourceGroup := id.ResourceGroup
	name := id.Path["virtualMachines"]

	resp, err := clients.SecurityCenter.ServerVulnerabilityAssessmentClient.Get(ctx, resourceGroup, "Microsoft.Compute", "virtualMachines", name)
	if err != nil {
		return nil, fmt.Errorf("reading Server Vulnerability Assessment (%s/%s): %+v", resourceGroup, name, err)
	}

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

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

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

resource "azurerm_virtual_network" "test" {
  name                = "acctestVNet-%[1]d"
  resource_group_name = azurerm_resource_group.test.name
  address_space       = ["192.168.1.0/24"]
  location            = azurerm_resource_group.test.location
}

resource "azurerm_subnet" "test" {
  name                 = "acctestSubnet-%[1]d"
  resource_group_name  = azurerm_resource_group.test.name
  virtual_network_name = azurerm_virtual_network.test.name
  address_prefixes     = ["192.168.1.0/24"]
}

resource "azurerm_network_interface" "test" {
  name                = "acctestNIC-%[1]d"
  location            = azurerm_resource_group.test.location
  resource_group_name = azurerm_resource_group.test.name

  ip_configuration {
    name                          = "vm-%[1]d"
    subnet_id                     = azurerm_subnet.test.id
    private_ip_address_allocation = "Dynamic"
  }
}

resource "azurerm_linux_virtual_machine" "test" {
  name                = "acctestVM-%[1]d"
  location            = azurerm_resource_group.test.location
  resource_group_name = azurerm_resource_group.test.name

  size                            = "Standard_B1s"
  admin_username                  = "testadmin"
  admin_password                  = "Password1234!"
  disable_password_authentication = false

  source_image_reference {
    publisher = "Canonical"
    offer     = "0001-com-ubuntu-server-jammy"
    sku       = "22_04-lts"
    version   = "latest"
  }

  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }

  network_interface_ids = [azurerm_network_interface.test.id]
}

resource "azurerm_security_center_subscription_pricing" "test" {
  tier          = "Standard"
  resource_type = "VirtualMachines"
  subplan       = "P2"
}

resource "azurerm_security_center_server_vulnerability_assessment" "test" {
  virtual_machine_id = azurerm_linux_virtual_machine.test.id
  depends_on         = [azurerm_security_center_subscription_pricing.test]
}
`, data.RandomInteger, data.Locations.Primary)
}

func (r ServerVulnerabilityAssessmentResource) requiresImport(data acceptance.TestData) string {
	config := r.basicCfg(data)
	return fmt.Sprintf(`
%s
resource "azurerm_security_center_server_vulnerability_assessment" "import" {
  virtual_machine_id = azurerm_security_center_server_vulnerability_assessment.test.virtual_machine_id
}
`, config)
}
