locals {
  # We want to share with:
  #  * The other accounts in our partition and environment
  #  * The common accounts
  #  * But not ourselves
  remote_accounts = toset([
    for account in concat(var.account_map[var.environment], var.account_map["common"]):
      account if account != var.aws_account_id
  ])
}

data "aws_availability_zones" "available" {
  state = "available"
}

resource "aws_ec2_transit_gateway" "tgw" {
  description = "Transit gateway for ${var.environment} in ${var.aws_partition}."
  amazon_side_asn = var.asn # may not need, but AWS recommends it for future proofing
  auto_accept_shared_attachments = "enable" # if we grant them access, they can attach.
  default_route_table_association = "enable"
  default_route_table_propagation = "enable"
  dns_support = "enable"

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

# We require a RAM to share the resource
resource "aws_ram_resource_share" "share_tgw" {
  name = var.name
  allow_external_principals = true # IMPORTANT

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

# Share the tgw
resource "aws_ram_resource_association" "share_tgw" {
  resource_arn       = aws_ec2_transit_gateway.tgw.arn
  resource_share_arn = aws_ram_resource_share.share_tgw.id
}

# ... with each other account
resource "aws_ram_principal_association" "share_with_accounts" {
  for_each = local.remote_accounts
  
  principal          = each.value
  resource_share_arn = aws_ram_resource_share.share_tgw.id
}


