// Target group to forward traffic from NLB to ALB
resource "aws_lb_target_group" "alb" {
  name        = "${var.name_prefix}-${var.alb_tg_name}"
  target_type = "alb"
  port        = 443
  protocol    = "TCP"
  vpc_id      = var.vpc_id
  tags        = var.tags
}

resource "aws_lb_target_group_attachment" "alb" {
  target_group_arn = aws_lb_target_group.alb.arn
  target_id        = var.alb_arn
  port             = 443
}

//NLB
resource "aws_eip" "nlb_eips" {
  for_each = toset(var.public_subnets_ids)
  domain   = "vpc"
}

resource "aws_lb" "nlb" {
  name               = "${var.name_prefix}-${var.nlb_name}"
  load_balancer_type = "network"
  security_groups    = var.security_groups

  tags = var.tags

  dynamic "subnet_mapping" {
    for_each = toset(var.public_subnets_ids)
    content {
      subnet_id     = subnet_mapping.value
      allocation_id = aws_eip.nlb_eips[subnet_mapping.value].id
    }
  }
}

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

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

// security group that allows access from NLB to ALB (not sure if needed)
resource "aws_security_group" "access_from_nlb" {
  name        = "${var.name_prefix}-${var.sg_name}"
  description = "Allow https from NLB EIPs"
  vpc_id      = var.vpc_id

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = formatlist("%s/32", [for ip in aws_eip.nlb_eips : ip.public_ip])
  }

  tags = merge(
    {
      Name             = "${var.name_prefix}-${var.sg_name}",
      "eiso-exception" = "aws.08.30",
    },
    var.tags
  )
}
