locals {
  access_type = var.is_public ? "public" : "private"
}

# Create route tables
resource "aws_route_table" "main" {
  vpc_id = var.vpc_id

  tags = merge(
    var.common_tags,
    {
      "Name" = format("%v-routetable-%v%v%v",
        var.name_prefix,
        local.access_type,
        var.custom_identifier,
        var.index,
      )
    },
  )
}

resource "aws_route_table_association" "main" {
  count          = length(var.subnets)
  subnet_id      = element(var.subnets, count.index)
  route_table_id = aws_route_table.main.id
}

resource "aws_route" "public_igw" {
  count                  = var.is_public ? (var.disable_default_route ? 0 : 1) : 0
  route_table_id         = aws_route_table.main.id
  destination_cidr_block = "0.0.0.0/0"
  gateway_id             = var.igw_id
}

resource "aws_route" "private_nat" {
  count                  = var.is_public ? 0 : (var.disable_default_route ? 0 : 1)
  route_table_id         = aws_route_table.main.id
  destination_cidr_block = "0.0.0.0/0"
  nat_gateway_id         = var.nat_gateway_id
}

