# WAF managed rulesets (doc/05 §2 WAF 全开).
resource "cloudflare_ruleset" "waf_managed" {
  zone_id = var.zone_id
  name    = "pangolin-waf-managed"
  kind    = "zone"
  phase   = "http_request_firewall_managed"

  rules {
    action      = "execute"
    description = "Cloudflare Managed Ruleset"
    enabled     = true
    expression  = "true"

    action_parameters {
      # Cloudflare Managed Ruleset (stable well-known ID).
      id = "efb7b8c949ac4650a09736fc376e9aee"
    }
  }

  rules {
    action      = "execute"
    description = "Cloudflare OWASP Core Ruleset"
    enabled     = true
    expression  = "true"

    action_parameters {
      # OWASP Core Ruleset (stable well-known ID).
      id = "4814384a9e5d4991b9815dcfc25d2f1f"
    }
  }
}

# Rate limiting (doc/05 §2 速率限制全开). Per-IP budget on the API surface.
resource "cloudflare_ruleset" "rate_limit" {
  zone_id = var.zone_id
  name    = "pangolin-rate-limit"
  kind    = "zone"
  phase   = "http_ratelimit"

  rules {
    action      = "block"
    description = "Per-IP rate limit on /v1/*"
    enabled     = true
    expression  = "(starts_with(http.request.uri.path, \"/v1/\"))"

    ratelimit {
      characteristics     = ["ip.src", "cf.colo.id"]
      period              = 60
      requests_per_period = var.rate_limit_requests_per_minute
      mitigation_timeout  = var.rate_limit_mitigation_seconds
    }
  }
}

# Bot management (doc/05 §2 bot 管理全开). Requires Bot Management / Super Bot
# Fight Mode on the plan; toggle with enable_bot_management.
resource "cloudflare_bot_management" "this" {
  count   = var.enable_bot_management ? 1 : 0
  zone_id = var.zone_id

  enable_js                       = true
  sbfm_definitely_automated       = "block"
  sbfm_likely_automated           = "managed_challenge"
  sbfm_verified_bots              = "allow"
  sbfm_static_resource_protection = false
  optimize_wordpress              = false
}
