resource "aws_wafv2_web_acl" "this" {
  count = var.enabled ? 1 : 0
  name  = var.name
  scope = local.scope

  default_action {
    dynamic "allow" {
      for_each = local.action_type == "allow" ? [1] : []
      content {}
    }
    dynamic "block" {
      for_each = local.action_type == "block" ? [1] : []
      content {}
    }
  }

  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "nova-waf-metrics"
    sampled_requests_enabled   = true
  }

  dynamic "rule" {
    for_each = var.rules
    content {
      name     = lookup(rule.value, "name", "custom-rule-${rule.key}")
      priority = lookup(rule.value, "priority", rule.key)
      override_action {
        none {}
      }
      statement {
        byte_match_statement {
          search_string         = lookup(rule.value, "search_string", "/")
          positional_constraint = "CONTAINS"
          field_to_match {
            single_header {
              name = "user-agent"
            }
          }
          text_transformation {
            priority = 0
            type     = "NONE"
          }
        }
      }
      visibility_config {
        cloudwatch_metrics_enabled = true
        metric_name                = "${lookup(rule.value, "name", "custom-rule-${rule.key}")}-metrics"
        sampled_requests_enabled   = true
      }
    }
  }
}