{% set config = merged_configs.get('aws_lb', {}) %}
{% set comments = compliance_comments.get('aws_lb', []) %}
# ------------------------------------------------------------------------------
# Application Load Balancer
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "aws_lb" "this" {
  name               = "{{ config.get('name', project_id ~ '-alb') }}"
  internal           = {{ config.get('internal', false) | lower }}
  load_balancer_type = "{{ config.get('load_balancer_type', 'application') }}"
  security_groups    = {{ config.get('security_groups', '[]') }}
  subnets            = {{ config.get('subnets', '[]') }}

  enable_deletion_protection = {{ config.get('enable_deletion_protection', true) | lower }}
  drop_invalid_header_fields = {{ config.get('drop_invalid_header_fields', true) | lower }}

  {% if config.get('access_logs_bucket') %}
  access_logs {
    bucket  = "{{ config.access_logs_bucket }}"
    prefix  = "{{ config.get('access_logs_prefix', project_id ~ '-alb') }}"
    enabled = true
  }
  {% endif %}

  tags = {
    Name      = "{{ config.get('name', project_id ~ '-alb') }}"
    ManagedBy = "complyform"
  }
}

resource "aws_lb_listener" "https" {
  load_balancer_arn = aws_lb.this.arn
  port              = {{ config.get('listener_port', 443) }}
  protocol          = "{{ config.get('listener_protocol', 'HTTPS') }}"
  ssl_policy        = "{{ config.get('ssl_policy', 'ELBSecurityPolicy-TLS13-1-2-2021-06') }}"
  certificate_arn   = {{ config.get('certificate_arn', 'null') }}

  default_action {
    type = "{{ config.get('default_action_type', 'fixed-response') }}"

    {% if config.get('default_action_type', 'fixed-response') == 'fixed-response' %}
    fixed_response {
      content_type = "text/plain"
      message_body = "Not Found"
      status_code  = "404"
    }
    {% endif %}

    {% if config.get('default_action_type') == 'forward' %}
    target_group_arn = {{ config.get('default_target_group_arn', 'null') }}
    {% endif %}
  }

  tags = {
    Name      = "{{ project_id }}-alb-https"
    ManagedBy = "complyform"
  }
}

# HTTP to HTTPS redirect
resource "aws_lb_listener" "http_redirect" {
  load_balancer_arn = aws_lb.this.arn
  port              = 80
  protocol          = "HTTP"

  default_action {
    type = "redirect"

    redirect {
      port        = "443"
      protocol    = "HTTPS"
      status_code = "HTTP_301"
    }
  }

  tags = {
    Name      = "{{ project_id }}-alb-http-redirect"
    ManagedBy = "complyform"
  }
}
