class AddEnumsToRules < ActiveRecord::Migration[8.1]
  def change
    # Add enum columns with default values
    add_column :rules, :waf_action, :integer, default: 0, null: false
    add_column :rules, :waf_rule_type, :integer, default: 0, null: false

    # Add indexes for enum columns
    add_index :rules, :waf_action
    add_index :rules, :waf_rule_type

    # Migrate existing data
    # Map action strings to integers (starting from 0 to match Rails enum convention)
    execute <<-SQL
      UPDATE rules
      SET waf_action = CASE action
        WHEN 'allow' THEN 0
        WHEN 'deny' THEN 1
        WHEN 'rate_limit' THEN 2
        WHEN 'redirect' THEN 3
        WHEN 'log' THEN 4
        WHEN 'challenge' THEN 5
        ELSE 0
      END;
    SQL

    # Map rule_type strings to integers
    execute <<-SQL
      UPDATE rules
      SET waf_rule_type = CASE rule_type
        WHEN 'network' THEN 0
        WHEN 'rate_limit' THEN 1
        WHEN 'path_pattern' THEN 2
        ELSE 0
      END;
    SQL
  end
end
