data "aws_region" "this" {}

data "dns_a_record_set" "this" {
  host = "${aws_mq_broker.this.id}.mq.${data.aws_region.this.region}.amazonaws.com"
}

locals {
  broker_node_indices = (
    var.deployment_mode == "CLUSTER_MULTI_AZ"
    ? toset(["0", "1", "2"])
    : toset(["0"])
  )
}

resource "aws_lb" "this" {
  provider = aws.this

  name               = "${var.name_prefix}-${var.name_suffix}"
  internal           = true
  load_balancer_type = "network"
  subnets            = var.subnet_ids
  ip_address_type    = "ipv4"

  dynamic "access_logs" {
    for_each = local.access_logs_enabled
    content {
      bucket  = var.access_logs_bucket_name
      prefix  = "elb/${var.access_logs_bucket_prefix}"
      enabled = true
    }
  }

  tags = {
    service = "ELB"
  }
}

resource "aws_lb_target_group" "this" {
  provider = aws.this

  name        = "${var.name_prefix}-${var.name_suffix}"
  port        = 5671
  protocol    = "TLS"
  vpc_id      = var.vpc_id
  target_type = "ip"

  health_check {
    protocol = "TCP"
    port     = 443
    interval = 30
  }

  lifecycle {
    create_before_destroy = true
  }

  tags = {
    service = "ELB"
  }
}

resource "aws_lb_target_group_attachment" "this" {
  for_each = local.broker_node_indices

  provider = aws.this

  target_group_arn = aws_lb_target_group.this.arn
  target_id        = data.dns_a_record_set.this.addrs[tonumber(each.key)]
  port             = 5671

  depends_on = [data.dns_a_record_set.this]
}

resource "aws_lb_listener" "this" {
  provider = aws.this

  load_balancer_arn = aws_lb.this.arn
  port              = 5671
  protocol          = "TLS"
  ssl_policy        = "ELBSecurityPolicy-TLS-1-2-Ext-2018-06"
  certificate_arn   = aws_acm_certificate.this.arn

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

  tags = {
    service = "ELB"
  }
}
