resource "aws_route53_resolver_endpoint" "private_resolver" {
  name      = "xdr_forward_to_dns"
  direction = "OUTBOUND"

  security_group_ids = [ aws_security_group.resolver_security_group.id ]

  dynamic "ip_address" {
    for_each = var.subnets

    content {
      subnet_id = ip_address.value
    }
  }

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

resource "aws_security_group" "resolver_security_group" {
  name        = "route53_resolver_outbound"
  description = "Allow DNS inbound traffic"
  vpc_id      = var.primary_vpc

  ingress {
    description = "DNS_UDP"
    from_port   = 53
    to_port     = 53
    protocol    = "udp"
    cidr_blocks = [ "10.0.0.0/8" ]
  }

  ingress {
    description = "DNS_TCP"
    from_port   = 53
    to_port     = 53
    protocol    = "tcp"
    cidr_blocks = [ "10.0.0.0/8" ]
  }

  egress {
    description = "DNS_UDP"
    from_port   = 53
    to_port     = 53
    protocol    = "udp"
    cidr_blocks = [ "10.0.0.0/8" ]
  }

  egress {
    description = "DNS_TCP"
    from_port   = 53
    to_port     = 53
    protocol    = "tcp"
    cidr_blocks = [ "10.0.0.0/8" ]
  }

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

resource "aws_route53_resolver_rule" "private" {
  domain_name          = var.dns_info["private"]["zone"]
  name                 = replace(var.dns_info["private"]["zone"], ".", "-")
  rule_type            = "FORWARD"
  resolver_endpoint_id = aws_route53_resolver_endpoint.private_resolver.id

  dynamic "target_ip" {
    for_each = var.inbound_resolver_endpoints

    content {
      ip = target_ip.value
    }
  }

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

resource "aws_route53_resolver_rule" "reverse" {
  domain_name          = var.dns_info["reverse"]["zone"]
  name                 = replace(var.dns_info["reverse"]["zone"], ".", "-")
  rule_type            = "FORWARD"
  resolver_endpoint_id = aws_route53_resolver_endpoint.private_resolver.id

  dynamic "target_ip" {
    for_each = var.inbound_resolver_endpoints

    content {
      ip = target_ip.value
    }
  }

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

resource "aws_route53_resolver_rule_association" "private_association" {
  for_each = toset(var.additional_vpcs)
  resolver_rule_id = aws_route53_resolver_rule.private.id
  vpc_id           = each.value
}

resource "aws_route53_resolver_rule_association" "reverse_association" {
  for_each = toset(var.additional_vpcs)
  resolver_rule_id = aws_route53_resolver_rule.reverse.id
  vpc_id           = each.value
}


