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

resource "azurerm_application_gateway" "this" {
  name                = "{{ config.get('name', project_id ~ '-appgw') }}"
  resource_group_name = var.resource_group_name
  location            = var.region

  sku {
    name     = "{{ config.get('sku_name', 'WAF_v2') }}"
    tier     = "{{ config.get('sku_tier', 'WAF_v2') }}"
    capacity = {{ config.get('capacity', 2) }}
  }

  gateway_ip_configuration {
    name      = "{{ project_id }}-gwip"
    subnet_id = "{{ config.get('subnet_id', '') }}"
  }

  frontend_port {
    name = "https-port"
    port = 443
  }

  frontend_ip_configuration {
    name                 = "{{ project_id }}-feip"
    public_ip_address_id = "{{ config.get('public_ip_address_id', '') }}"
  }

  backend_address_pool {
    name = "{{ project_id }}-beap"
  }

  backend_http_settings {
    name                  = "{{ project_id }}-http-settings"
    cookie_based_affinity = "{{ config.get('cookie_based_affinity', 'Disabled') }}"
    port                  = 443
    protocol              = "Https"
    request_timeout       = {{ config.get('request_timeout', 60) }}
  }

  http_listener {
    name                           = "{{ project_id }}-listener"
    frontend_ip_configuration_name = "{{ project_id }}-feip"
    frontend_port_name             = "https-port"
    protocol                       = "Https"
    ssl_certificate_name           = "{{ config.get('ssl_certificate_name', project_id ~ '-cert') }}"
  }

  request_routing_rule {
    name                       = "{{ project_id }}-rule"
    priority                   = {{ config.get('rule_priority', 100) }}
    rule_type                  = "Basic"
    http_listener_name         = "{{ project_id }}-listener"
    backend_address_pool_name  = "{{ project_id }}-beap"
    backend_http_settings_name = "{{ project_id }}-http-settings"
  }

  ssl_policy {
    policy_type = "{{ config.get('ssl_policy_type', 'Predefined') }}"
    policy_name = "{{ config.get('ssl_policy_name', 'AppGwSslPolicy20220101') }}"
  }

  {% if config.get('sku_tier') in ['WAF_v2', 'WAF'] %}
  waf_configuration {
    enabled          = true
    firewall_mode    = "{{ config.get('waf_mode', 'Prevention') }}"
    rule_set_type    = "OWASP"
    rule_set_version = "{{ config.get('waf_rule_set_version', '3.2') }}"
  }
  {% endif %}

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