# frozen_string_literal: true

# Migrate add_header rules to use allow action with tags/headers in metadata
#
# Old pattern:
#   waf_action: add_header (5)
#   metadata: { header_name: "X-Bot-Agent", header_value: "googlebot" }
#
# New pattern:
#   waf_action: allow (1)
#   metadata: {
#     headers: { "X-Bot-Agent" => "googlebot" },
#     tags: ["bot:googlebot"]
#   }
#
class MigrateAddHeaderRulesToAllowWithTags < ActiveRecord::Migration[8.1]
  def up
    # Change all add_header (5) rules to allow (1)
    # Keep metadata as-is for now - will be handled by Rule helper methods
    execute <<-SQL
      UPDATE rules
      SET waf_action = 1  -- allow
      WHERE waf_action = 5  -- add_header
    SQL
  end

  def down
    # This rollback is conservative - only revert rules that clearly came from add_header
    # (have header_name/header_value in metadata but not headers)
    execute <<-SQL
      UPDATE rules
      SET waf_action = 5  -- add_header
      WHERE waf_action = 1  -- allow
        AND metadata ? 'header_name'
        AND metadata ? 'header_value'
        AND NOT metadata ? 'headers'
    SQL
  end
end
