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

# This module is a thin wrapper that invokes the shared-bandwidth module once
# per dataplane account (up to 3). Each account gets its own alicloud provider
# instance so the bandwidth package is bootstrapped in the correct account.

# Terraform does not support dynamic provider counts, so we statically define
# three alicloud provider aliases (dp_0, dp_1, dp_2) and guard each module
# invocation with a count expression.
provider "alicloud" {
  profile = var.dataplane_accounts.0
  region  = var.cloud_region
  alias   = "dp_0"
}

provider "alicloud" {
  # Fall back to the first account when a second account is not provided.
  profile = try(var.dataplane_accounts.1, var.dataplane_accounts.0)
  region  = var.cloud_region
  alias   = "dp_1"
}

provider "alicloud" {
  # Fall back to the first account when a third account is not provided.
  profile = try(var.dataplane_accounts.2, var.dataplane_accounts.0)
  region  = var.cloud_region
  alias   = "dp_2"
}

variable "dataplane_accounts" {
  type = list(string)

  validation {
    condition     = length(var.dataplane_accounts) > 0
    error_message = "at least one dataplane account needs to be provided"
  }
}

variable "cloud_region" {
  type = string
}

locals {
  dp_accounts = length(var.dataplane_accounts)
}

# Ensure a shared bandwidth package exists in the first dataplane account.
module "bandwidth_package_0" {
  count  = local.dp_accounts > 0 ? 1 : 0
  source = "../../alicloud_modules/shared-bandwidth"
  providers = {
    alicloud = alicloud.dp_0
  }
  region = var.cloud_region
}

# Ensure a shared bandwidth package exists in the second dataplane account (if any).
module "bandwidth_package_1" {
  count  = local.dp_accounts > 1 ? 1 : 0
  source = "../../alicloud_modules/shared-bandwidth"
  providers = {
    alicloud = alicloud.dp_1
  }
  region = var.cloud_region
}

# Ensure a shared bandwidth package exists in the third dataplane account (if any).
module "bandwidth_package_2" {
  count  = local.dp_accounts > 2 ? 1 : 0
  source = "../../alicloud_modules/shared-bandwidth"
  providers = {
    alicloud = alicloud.dp_2
  }
  region = var.cloud_region
}

# Collect all bandwidth package IDs into a compact list, omitting accounts that
# were not provisioned. Consumed by upstream modules (e.g. dataplane-manager).
output "shared_bandwidth_package_ids" {
  value = compact([
    try(module.bandwidth_package_0.0.shared_bandwidth_package_id, ""),
    try(module.bandwidth_package_1.0.shared_bandwidth_package_id, ""),
    try(module.bandwidth_package_2.0.shared_bandwidth_package_id, ""),
  ])
}
