resource "aws_vpc" "this" {
  count = var.enabled ? 1 : 0
  cidr_block = local.cidr_block
  tags = {
    Name = local.name_tag
  }

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_subnet" "this" {
  count             = length(local.az_list)
  vpc_id            = aws_vpc.this[0].id
  cidr_block        = local.subnet_cidrs[count.index]
  availability_zone = local.az_list[count.index]
  tags = {
    Name = "${local.name_tag}-subnet-${count.index}"
  }
}

resource "aws_internet_gateway" "this" {
  count = var.enabled ? 1 : 0
  vpc_id = aws_vpc.this[0].id
  tags = {
    Name = "${local.name_tag}-igw"
  }
}

resource "aws_route_table" "this" {
  count = var.enabled ? 1 : 0
  vpc_id = aws_vpc.this[0].id
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.this[0].id
  }
  tags = {
    Name = "${local.name_tag}-rt"
  }
}

resource "aws_route_table_association" "this" {
  count          = length(local.az_list)
  subnet_id      = aws_subnet.this[count.index].id
  route_table_id = aws_route_table.this[0].id
}
