resource "aws_lb_listener_rule" "return_404_for_icons" {
  listener_arn = module.ows_url_shortener_fargate_environment.fargate_load_balancer_https_listener_arn
  priority     = 10

  action {
    type = "fixed-response"
    fixed_response {
      content_type = "text/plain"
      message_body = "Not Found"
      status_code  = "404"
    }
  }

  condition {
    path_pattern {
      values = [
        "/favicon.ico",
        "/apple-touch-icon.png",
        "/apple-touch-icon-precomposed.png"
      ]
    }
  }
}

resource "aws_lb_listener_rule" "forward_main" {
  listener_arn = module.ows_url_shortener_fargate_environment.fargate_load_balancer_https_listener_arn
  priority     = 20

  action {
    type             = "forward"
    target_group_arn = module.ows_url_shortener_fargate_environment.fargate_target_group_arn
  }

  condition {
    path_pattern {
      values = [
        "/redirect/*",
      ]
    }
  }
}

resource "aws_lb_listener_rule" "redirect" {
  listener_arn = module.ows_url_shortener_fargate_environment.fargate_load_balancer_https_listener_arn
  priority     = 100

  action {
    type = "redirect"

    redirect {
      status_code = "HTTP_301"
      host        = "#{host}"
      path        = "/redirect/#{path}"
      query       = "#{query}"
      protocol    = "#{protocol}"
      port        = "#{port}"
    }
  }

  condition {
    path_pattern {
      values = ["/*"]
    }
  }
}
