resource "aws_lb" "main" {
  name               = "${local.name_prefix}-external-images-api"
  internal           = false
  load_balancer_type = "application"
  subnets            = data.aws_subnets.public_subnets.ids
  idle_timeout       = 60
  ip_address_type    = "ipv4"

  security_groups = [
    data.aws_security_group.alb.id,
    data.aws_security_group.public_access.id
  ]

  tags = {
    project                  = "API",
    service                  = "Load Balancing",
    plat_env_project_service = "${local.aggregated_tag}_API_LB"
  }

  access_logs {
    bucket  = data.aws_s3_bucket.security_logs.bucket
    prefix  = "elb/${local.name_prefix}-external-main"
    enabled = true
  }
}

resource "aws_lb_listener" "main" {
  load_balancer_arn = aws_lb.main.arn
  port              = 80
  protocol          = "HTTP"

  default_action {
    type = "fixed-response"
    fixed_response {
      content_type = "text/plain"
      message_body = "Access denied"
      status_code  = "403"
    }
  }

  tags = {
    project                  = "API",
    service                  = "Load Balancing",
    plat_env_project_service = "${local.aggregated_tag}_API_LB"
  }
}

resource "aws_lb_target_group" "main" {
  name                 = "${local.name_prefix}-images-api"
  port                 = 80
  protocol             = "HTTP"
  vpc_id               = data.aws_vpc.main.id
  deregistration_delay = 60
  target_type          = "ip"

  health_check {
    path                = "/health"
    port                = "traffic-port"
    protocol            = "HTTP"
    matcher             = 200
    interval            = 30
    timeout             = 5
    unhealthy_threshold = 3
    healthy_threshold   = 3
  }

  tags = {
    project                  = "API",
    service                  = "Load Balancing",
    plat_env_project_service = "${local.aggregated_tag}_API_LB"
  }

  # fixes: Error deleting Target Group: ResourceInUse
  lifecycle {
    create_before_destroy = true
    ignore_changes        = [name]
  }
}

resource "aws_lb_listener_rule" "main" {
  listener_arn = aws_lb_listener.main.arn

  priority = 2

  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.main.arn
  }

  condition {
    http_header {
      http_header_name = "X-Custom-Header"
      values = [
        "random-string-${random_string.custom_header_prefix.result}"
      ]
    }
  }
}
