# Precondition: ram_principals requires ram_share_name ======================
# Caught at plan time so the caller gets a clear error rather than silent
# no-op RAM associations.

resource "terraform_data" "ram_precondition" {
  lifecycle {
    precondition {
      condition     = !(length(var.ram_principals) > 0 && !local.enable_ram_share)
      error_message = "ram_principals is set but ram_share_name is null. Set ram_share_name to enable RAM sharing."
    }
  }
}

# Transit Gateway ============================================================

resource "aws_ec2_transit_gateway" "this" {
  description                     = var.description
  amazon_side_asn                 = var.amazon_side_asn
  auto_accept_shared_attachments  = var.auto_accept_shared_attachments
  default_route_table_association = var.default_route_table_association
  default_route_table_propagation = var.default_route_table_propagation
  dns_support                     = var.dns_support
  vpn_ecmp_support                = var.vpn_ecmp_support
  multicast_support               = var.multicast_support

  tags = merge(local.tags, { Name = var.name })

  # lifecycle {
  #   # TGW deletion drops every attachment — require explicit override to destroy.
  #   prevent_destroy = true
  # }
}

# Additional route tables ----------------------------------------------------

resource "aws_ec2_transit_gateway_route_table" "this" {
  for_each = var.route_tables

  transit_gateway_id = aws_ec2_transit_gateway.this.id

  tags = merge(local.tags, { Name = each.value.name })
}

# RAM resource share ---------------------------------------------------------

resource "aws_ram_resource_share" "this" {
  for_each = local.enable_ram_share ? { share = true } : {}

  name                      = var.ram_share_name
  allow_external_principals = var.ram_allow_external_principals

  tags = local.tags
}

resource "aws_ram_resource_association" "this" {
  for_each = local.enable_ram_share ? { share = true } : {}

  resource_arn       = aws_ec2_transit_gateway.this.arn
  resource_share_arn = aws_ram_resource_share.this["share"].arn
}

resource "aws_ram_principal_association" "this" {
  for_each = toset(var.ram_principals)

  principal          = each.value
  resource_share_arn = aws_ram_resource_share.this["share"].arn

  depends_on = [aws_ram_resource_share.this]
}
