class CreateTagNameSanitisationRules < ActiveRecord::Migration[8.0]
  def up
    create_table :tag_name_sanitisation_rules, id: :integer, primary_key: :priority do |t|
      t.string :source_pattern, null: false
      t.string :replacement, null: false
      t.timestamps
      t.datetime :discarded_at
      t.index :source_pattern, unique: true
      t.index :discarded_at
    end

    now = ActiveRecord::Base.connection.quote(Time.current)
    execute <<~SQL
      INSERT INTO
        tag_name_sanitisation_rules(priority, source_pattern, replacement, created_at, updated_at)
      VALUES
        (10, '\\\\*',           '_',         #{ now }, #{ now })
      , (20, '\\\\?',           '_',         #{ now }, #{ now })
      , (25, '\\\\/',           '_',         #{ now }, #{ now })
      , (30, '_+',              '_',         #{ now }, #{ now })
      , (40, '_$',              '',          #{ now }, #{ now })
      , (45, '^([^:]+\\\\:)?_', '\\\\1',     #{ now }, #{ now })
      , (50, '^([^:]+\\\\:)?$', '\\\\1null', #{ now }, #{ now })
      ;
    SQL
  end

  def down
    drop_table :tag_name_sanitisation_rules
  end
end
