class CreatePostUrlSanitisationRules < ActiveRecord::Migration[8.0]
  class PostUrlSanitisationRule < ActiveRecord::Base
    self.table_name = 'post_url_sanitisation_rules'
  end

  def up
    create_table :post_url_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 = Time.current

    PostUrlSanitisationRule.insert_all!([
        { priority: 10,
          source_pattern: '\Ahttps?://youtu\.be/([^/?#]+)(?:[?#].*)?\z',
          replacement: 'https://www.youtube.com/watch?v=\1',
          created_at: now,
          updated_at: now },
        { priority: 20,
          source_pattern: '\Ahttps?://(?:www\.|m\.)?youtube\.com/live/([^/?#]+)(?:[?#].*)?\z',
          replacement: 'https://www.youtube.com/watch?v=\1',
          created_at: now,
          updated_at: now },
        { priority: 30,
          source_pattern: '\Ahttps?://(?:www\.|m\.)?youtube\.com/shorts/([^/?#]+)(?:[?#].*)?\z',
          replacement: 'https://www.youtube.com/watch?v=\1',
          created_at: now,
          updated_at: now },
        { priority: 40,
          source_pattern: '\Ahttps?://(?:www\.|m\.)?youtube\.com/embed/([^/?#]+)(?:[?#].*)?\z',
          replacement: 'https://www.youtube.com/watch?v=\1',
          created_at: now,
          updated_at: now },
        { priority: 50,
          source_pattern:
              '\Ahttps?://(?:www\.|m\.)?youtube\.com/watch\?(?:[^#&]+&)*v=([^&#]+)(?:[&#].*)?\z',
          replacement: 'https://www.youtube.com/watch?v=\1',
          created_at: now,
          updated_at: now },
        { priority: 60,
          source_pattern: '\Ahttps?://nico\.ms/([^/?#]+)(?:[?#].*)?\z',
          replacement: 'https://www.nicovideo.jp/watch/\1',
          created_at: now,
          updated_at: now },
        { priority: 70,
          source_pattern: '\Ahttps?://(?:www\.)?nicovideo\.jp/watch/([^?#/]+)(?:[?#].*)?\z',
          replacement: 'https://www.nicovideo.jp/watch/\1',
          created_at: now,
          updated_at: now }])
  end

  def down
    drop_table :post_url_sanitisation_rules
  end
end
