resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"

  enable_dns_hostnames = true

  tags = {
    Name = "vpc-${var.environment}"
    Env = var.environment
  }
}

resource "aws_subnet" "subnets" {
  vpc_id     = aws_vpc.main.id
  for_each   = var.vpc_subnets
  cidr_block = each.value.cidr_block
  availability_zone = each.value.availability_zone

  map_public_ip_on_launch = true

  tags = {
    Name = "${each.key}-${var.environment}"
    Env = var.environment
    "kubernetes.io/cluster/eks-cluster-${var.environment}" = "owned"
  }
}

// The internet gateway is required so nodes can connect to the control plane
resource "aws_internet_gateway" "nat_gateway" {
  vpc_id = aws_vpc.main.id
}

resource "aws_route_table" "nat_gateway" {
  vpc_id = aws_vpc.main.id
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.nat_gateway.id
  }
}

resource "aws_route_table_association" "nat_gateway" {
  for_each = aws_subnet.subnets

  subnet_id = each.value.id
  route_table_id = aws_route_table.nat_gateway.id
}