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

module "vpc" {
  source = "terraform-aws-modules/vpc/aws"
  version = "~> v2.70"
  name = var.name
  cidr = var.cidr

  azs = slice(data.aws_availability_zones.available.names,0,3)

  private_subnets = [
      cidrsubnet(var.cidr,3,0),
      cidrsubnet(var.cidr,3,1),
      cidrsubnet(var.cidr,3,2),
  ]

  # Potentially, we could route all accounts through the transit gateway to
  # save costs and provide one point of exit to the Internet. But at this time,
  # I'm keeping it consistent with our legacy accounts.
  #
  # If we decide to do that, we should consider either dropping to a /23 per customer,
  # or a /24 for each subnet (seems wasteful).
  #public_subnets = [ ]
  public_subnets = [
      cidrsubnet(var.cidr,3,4),
      cidrsubnet(var.cidr,3,5),
      cidrsubnet(var.cidr,3,6),
  ]

  enable_nat_gateway = true
  enable_dns_hostnames = true

  enable_ec2_endpoint              = true
  ec2_endpoint_private_dns_enabled = true
  ec2_endpoint_security_group_ids  =  [ module.aws_endpoints_sg.this_security_group_id ]

  dhcp_options_domain_name = var.dns_info["private"]["zone"]

  tags = merge(var.standard_tags, var.tags)

  nat_eip_tags = {
    "eip_type" = "natgw"
    Name = var.name
  }
}

resource "aws_flow_log" "flowlogs" {
  iam_role_arn    = "arn:${var.aws_partition}:iam::${var.aws_account_id}:role/aws_services/flowlogs"
  log_destination = "arn:${var.aws_partition}:logs:${var.aws_region}:${var.aws_account_id}:log-group:vpc_flow_logs"

  traffic_type    = "REJECT" # ALL is very noisy, and CIS only requires rejects.
  vpc_id          = module.vpc.vpc_id
  tags            = merge(var.standard_tags, var.tags)
}

# CIS 4.3 - Default security group should restrict all traffic
#
# This resource is special, and clears out existing rules. See:
# See https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/default_security_group
resource "aws_default_security_group" "default" {
  vpc_id = module.vpc.vpc_id
  tags = merge(var.standard_tags, var.tags)
}
