// ----------------------------------------------------------------------------
//
//     ***     AUTO GENERATED CODE    ***    AUTO GENERATED CODE     ***
//
// ----------------------------------------------------------------------------
//
//     This file is automatically generated by Magic Modules and manual
//     changes will be clobbered when the file is regenerated.
//
//     Please read more about how to change this file at
//     https://www.github.com/huaweicloud/magic-modules
//
// ----------------------------------------------------------------------------

package flexibleengine

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"

	"github.com/chnsz/golangsdk"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccNatDnat_basic(t *testing.T) {
	randSuffix := acctest.RandString(5)
	resourceName := "flexibleengine_nat_dnat_rule_v2.dnat"

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckNatDnatDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccNatV2DnatRule_basic(randSuffix),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckNatDnatExists(),
					resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"),
					resource.TestCheckResourceAttr(resourceName, "description", "created by terraform acc test"),
					resource.TestCheckResourceAttr(resourceName, "status", "ACTIVE"),
				),
			},
			{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func TestAccNatDnat_protocol(t *testing.T) {
	randSuffix := acctest.RandString(5)
	resourceName := "flexibleengine_nat_dnat_rule_v2.dnat"

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckNatDnatDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccNatV2DnatRule_protocol(randSuffix),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckNatDnatExists(),
					resource.TestCheckResourceAttr(resourceName, "protocol", "any"),
					resource.TestCheckResourceAttr(resourceName, "description", "created by terraform acc test"),
					resource.TestCheckResourceAttr(resourceName, "status", "ACTIVE"),
				),
			},
			{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func testAccCheckNatDnatDestroy(s *terraform.State) error {
	config := testAccProvider.Meta().(*Config)
	client, err := config.NatV2Client(OS_REGION_NAME)
	if err != nil {
		return fmt.Errorf("Error creating sdk client, err=%s", err)
	}

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "flexibleengine_nat_dnat_rule_v2" {
			continue
		}

		url, err := replaceVarsForTest(rs, "dnat_rules/{id}")
		if err != nil {
			return err
		}
		url = client.ServiceURL(url)

		_, err = client.Get(
			url, nil,
			&golangsdk.RequestOpts{MoreHeaders: map[string]string{"Accept": "application/json"}})
		if err == nil {
			return fmt.Errorf("flexibleengine_nat_dnat_rule_v2 still exists at %s", url)
		}
	}

	return nil
}

func testAccCheckNatDnatExists() resource.TestCheckFunc {
	return func(s *terraform.State) error {
		config := testAccProvider.Meta().(*Config)
		client, err := config.NatV2Client(OS_REGION_NAME)
		if err != nil {
			return fmt.Errorf("Error creating sdk client, err=%s", err)
		}

		rs, ok := s.RootModule().Resources["flexibleengine_nat_dnat_rule_v2.dnat"]
		if !ok {
			return fmt.Errorf("Error checking flexibleengine_nat_dnat_rule_v2.dnat exist, err=not found flexibleengine_nat_dnat_rule_v2.dnat")
		}

		url, err := replaceVarsForTest(rs, "dnat_rules/{id}")
		if err != nil {
			return fmt.Errorf("Error checking flexibleengine_nat_dnat_rule_v2.dnat exist, err=building url failed: %s", err)
		}
		url = client.ServiceURL(url)

		_, err = client.Get(
			url, nil,
			&golangsdk.RequestOpts{MoreHeaders: map[string]string{"Accept": "application/json"}})
		if err != nil {
			if _, ok := err.(golangsdk.ErrDefault404); ok {
				return fmt.Errorf("flexibleengine_nat_dnat_rule_v2.dnat is not exist")
			}
			return fmt.Errorf("Error checking flexibleengine_nat_dnat_rule_v2.dnat exist, err=send request failed: %s", err)
		}
		return nil
	}
}

func testAccNatV2DnatRule_base(suffix string) string {
	return fmt.Sprintf(`
data "flexibleengine_availability_zones" "test" {}

data "flexibleengine_compute_flavors_v2" "test" {
  availability_zone = data.flexibleengine_availability_zones.test.names[0]
  performance_type  = "normal"
  cpu_core          = 2
  memory_size       = 4
}

data "flexibleengine_images_image_v2" "test" {
  name        = "OBS Ubuntu 18.04"
  most_recent = true
}

resource "flexibleengine_networking_floatingip_v2" "fip_1" {
}

resource "flexibleengine_compute_instance_v2" "instance_1" {
  name              = "instance-acc-test-%s"
  image_id          = data.flexibleengine_images_image_v2.test.id
  flavor_id         = data.flexibleengine_compute_flavors_v2.test.flavors[0]
  security_groups   = ["default"]
  availability_zone = data.flexibleengine_availability_zones.test.names[0]

  network {
    uuid = flexibleengine_vpc_subnet_v1.subnet_1.id
  }

  tags = {
    foo = "bar"
  }
}
`, suffix)
}

func testAccNatV2DnatRule_basic(suffix string) string {
	return fmt.Sprintf(`
%s

%s

resource "flexibleengine_nat_dnat_rule_v2" "dnat" {
  nat_gateway_id = flexibleengine_nat_gateway_v2.nat_1.id
  floating_ip_id = flexibleengine_networking_floatingip_v2.fip_1.id
  private_ip     = flexibleengine_compute_instance_v2.instance_1.network.0.fixed_ip_v4
  protocol       = "tcp"
  description    = "created by terraform acc test"
  internal_service_port = 80
  external_service_port = 8080
}
`, testAccNatV2Gateway_basic(suffix), testAccNatV2DnatRule_base(suffix))
}

func testAccNatV2DnatRule_protocol(suffix string) string {
	return fmt.Sprintf(`
%s

%s

resource "flexibleengine_nat_dnat_rule_v2" "dnat" {
  nat_gateway_id = flexibleengine_nat_gateway_v2.nat_1.id
  floating_ip_id = flexibleengine_networking_floatingip_v2.fip_1.id
  private_ip     = flexibleengine_compute_instance_v2.instance_1.network.0.fixed_ip_v4
  protocol       = "any"
  description    = "created by terraform acc test"
  internal_service_port = 0
  external_service_port = 0
}
`, testAccNatV2Gateway_basic(suffix), testAccNatV2DnatRule_base(suffix))
}
