# TGW VPC Attachment ===========================================================
# Attaches the VPC to Transit Gateway using the designated attachment subnets.
# Default route table association and propagation are disabled when a custom
# route table ID is provided, allowing explicit control over TGW routing.

resource "aws_ec2_transit_gateway_vpc_attachment" "this" {
  transit_gateway_id = var.transit_gateway_id
  vpc_id             = var.vpc_id
  subnet_ids         = var.subnet_ids

  appliance_mode_support                          = var.appliance_mode_support
  dns_support                                     = var.dns_support
  ipv6_support                                    = var.ipv6_support
  transit_gateway_default_route_table_association = var.transit_gateway_route_table_id == null
  transit_gateway_default_route_table_propagation = var.transit_gateway_route_table_id == null

  tags = merge(var.tags, local.module_tags, {
    Name          = var.name
    resource-type = "tgw-attachment"
  })
}

# TGW Route Table Association ================================================
# Associates the attachment to a custom TGW route table.
# Skipped when transit_gateway_route_table_id is null, falling back to the
# TGW default route table association set on the attachment above.

resource "aws_ec2_transit_gateway_route_table_association" "this" {
  for_each = var.transit_gateway_route_table_id != null ? { assoc = true } : {}

  transit_gateway_attachment_id  = aws_ec2_transit_gateway_vpc_attachment.this.id
  transit_gateway_route_table_id = var.transit_gateway_route_table_id
}

# TGW Route Table Propagation ================================================
# Propagates the VPC CIDRs into the TGW route table so other attachments
# can route back to this VPC. Skipped when transit_gateway_route_table_id is null.

resource "aws_ec2_transit_gateway_route_table_propagation" "this" {
  for_each = var.transit_gateway_route_table_id != null ? { prop = true } : {}

  transit_gateway_attachment_id  = aws_ec2_transit_gateway_vpc_attachment.this.id
  transit_gateway_route_table_id = var.transit_gateway_route_table_id
}

# VPC Route Table Entries ====================================================
# Adds TGW as the next hop for each destination CIDR across all VPC route tables.
# depends_on ensures the attachment is fully available before routes are created,
# avoiding the InvalidTransitGatewayID.NotFound error on fresh TGW deployments.

resource "aws_route" "tgw" {
  for_each = local.route_map

  route_table_id         = each.value.rt_id
  destination_cidr_block = each.value.cidr
  transit_gateway_id     = var.transit_gateway_id

  depends_on = [aws_ec2_transit_gateway_vpc_attachment.this]
}
