# This module idempotently ensures that a shared bandwidth package exists in the
# target Alicloud account and region. It is designed to be called once per
# dataplane account. The package is created via the Alicloud CLI when absent,
# because the Terraform provider does not support adopting pre-existing resources.

terraform {
  required_providers {
    alicloud = {
      source  = "aliyun/alicloud"
      version = ">= 1.268"
    }
  }
}

# The region is passed in so the CLI call targets the correct endpoint.
variable "region" {
  type = string
}

# Resolve the current account ID to use as the CLI --profile value.
data "alicloud_account" "current" {}

# Check whether a shared bandwidth package already exists before attempting creation.
data "alicloud_common_bandwidth_packages" "pre" {}

locals {
  dataplane_account = data.alicloud_account.current.id
  # True when no bandwidth package is found; used to gate the CLI create call.
  create_bw_package = length(data.alicloud_common_bandwidth_packages.pre.ids) == 0
}

# Create a shared bandwidth package via the Alicloud CLI only when one does not
# already exist. Using null_resource + local-exec avoids re-creating the package
# on subsequent applies (ignore_changes = all).
resource "null_resource" "create_bw_package_if_not_exist" {
  triggers = {
    create_bw_package = local.create_bw_package
    region            = var.region
  }

  # Never modify or destroy this resource after creation; it is a one-time bootstrap.
  lifecycle {
    ignore_changes = all
  }

  provisioner "local-exec" {
    interpreter = ["bash", "-c"]
    command     = <<-EOT
        set -eou pipefail
        if [[ "${local.create_bw_package}" == "false" ]]; then
            exit 0
        fi
        # Create a 1 Gbps pay-by-traffic shared bandwidth package.
        aliyun vpc CreateCommonBandwidthPackage \
            --profile ${local.dataplane_account} \
            --region ${var.region} \
            --Bandwidth 1000 \
            --InternetChargeType "PayByTraffic"
    EOT
    when        = create
  }
}

# Re-query after the potential create so we always have a valid ID to output.
# The postcondition acts as a hard guard — apply fails if no package is found.
data "alicloud_common_bandwidth_packages" "post" {
  depends_on = [null_resource.create_bw_package_if_not_exist]

  lifecycle {
    postcondition {
      condition     = length(self.ids) > 0
      error_message = "bandwidth packages not found in ${local.dataplane_account}(${var.region})"
    }
  }
}

# Return the ID of the shared bandwidth package. Prefer the pre-existing one to
# avoid a second API call, falling back to the newly created one.
output "shared_bandwidth_package_id" {
  value = try(
    data.alicloud_common_bandwidth_packages.pre.ids.0,
    data.alicloud_common_bandwidth_packages.post.ids.0,
  )
}