# KeyCloak Needs an NLB:
#   * ALB/ELB can't terminate SSL, because Keycloak needs the certificate
#   * Because they don't terminate SSL, they can't provide X-forwarded-for, and keycloak needs the source IP
#   * Therefore, we use an NLB and preserve the source IP.
module "public_dns_record" {
  source = "../../submodules/dns/public_ALIAS_record"

  name = "keycloak.${var.dns_info["public"]["zone"]}"
  target_dns_name = aws_lb.external.dns_name
  target_zone_id  = aws_lb.external.zone_id
  dns_info = var.dns_info

  providers = {
    aws.mdr-common-services-commercial = aws.mdr-common-services-commercial
  }
}

#module "public_dns_record_2" {
#  # A second dns record that can be used after configuring the XDR realm
#  source = "../../submodules/dns/public_ALIAS_record"
#
#  name = "auth.${var.dns_info["public"]["zone"]}"
#  target_dns_name = aws_lb.external.dns_name
#  target_zone_id  = aws_lb.external.zone_id
#  dns_info = var.dns_info
#
#  providers = {
#    aws.mdr-common-services-commercial = aws.mdr-common-services-commercial
#  }
#}

resource "aws_lb" "external" {
  name = "keycloak-external-nlb"
  load_balancer_type = "network"
  internal = false
  subnets = var.public_subnets

  access_logs {
    bucket  = "xdr-elb-${ var.environment }"
    enabled = true
  }

  enable_cross_zone_load_balancing = true
  idle_timeout                = 300

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

resource "aws_lb_listener" "nlb_443" {
  load_balancer_arn = aws_lb.external.arn
  port              = "443"
  protocol          = "TCP"

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.external.arn
  }
}

resource "aws_lb_target_group" "external" {
  name     = "keycloak-external-nlb"
  port     = 8443
  protocol = "TCP"
  vpc_id   = var.vpc_id
  target_type = "instance"

  health_check {
    enabled = true
    #healthy_threshold   = 3
    #unhealthy_threshold = 2
    timeout = 10
    interval = 10
    #matcher = "200,302"
    path = "/"
    protocol = "HTTPS"
  }

  stickiness {
    enabled = true
    type = "source_ip" # only option for NLBs
  }
}

# Create a new load balancer attachment
resource "aws_lb_target_group_attachment" "external_attachment" {
  count = var.keycloak_instance_count
  target_group_arn = aws_lb_target_group.external.arn
  target_id = aws_instance.instance[count.index].id
}
