# WAF Rules for Application Gateway
# Configures Web Application Firewall rules for security

resource "azurerm_web_application_firewall_policy" "main" {
  name                = "${var.cluster_name}-waf-policy"
  resource_group_name = var.resource_group_name
  location            = var.location

  # Policy settings
  policy_settings {
    enabled                     = true
    mode                        = var.environment == "prod" ? "Prevention" : "Detection"
    request_body_check          = true
    max_request_body_size_in_kb = 128
    file_upload_limit_in_mb     = 100
  }

  # Managed rules (use default OWASP + BotManager rule sets, no deprecated overrides)
  managed_rules {
    # OWASP Core Rule Set
    managed_rule_set {
      type    = "OWASP"
      version = "3.2"
    }

    # Bot Protection
    managed_rule_set {
      type    = "Microsoft_BotManagerRuleSet"
      version = "1.0"
    }
  }

  # Custom rules
  # Note: RateLimitRule requires group_by_user_session which may not be supported in current provider version
  # Uncomment and configure when provider supports it, or use Azure Portal/CLI to configure rate limiting
  # custom_rules {
  #   name      = "BlockHighRateRequests"
  #   priority  = 1
  #   rule_type = "RateLimitRule"
  #   action    = "Block"
  #   rate_limit_threshold = 100
  # }

  # Custom rule to block suspicious IPs (only if IPs are provided)
  # Note: If blocked_ips is empty, this rule is effectively disabled
  dynamic "custom_rules" {
    for_each = length(var.blocked_ips) > 0 ? [1] : []
    content {
    name      = "BlockSuspiciousIPs"
    priority  = 2
    rule_type = "MatchRule"
    action    = "Block"
    
    match_conditions {
      match_variables {
        variable_name = "RemoteAddr"
      }
      operator           = "IPMatch"
      match_values       = var.blocked_ips
      negation_condition = false
      }
    }
  }

  custom_rules {
    name      = "AllowSpecificMethods"
    priority  = 3
    rule_type = "MatchRule"
    action    = "Allow"
    
    match_conditions {
      match_variables {
        variable_name = "RequestMethod"
      }
      operator           = "Contains"
      match_values       = ["GET", "POST", "OPTIONS"]
      negation_condition = false
    }
  }
}

# Variables
variable "blocked_ips" {
  description = "List of IP addresses/CIDR blocks to block"
  type        = list(string)
  default     = []
}

# Variables environment, cluster_name, resource_group_name, and location
# are defined in variables.tf

