class AddDiscardToPostTags < ActiveRecord::Migration[8.0]
  def up
    execute <<~SQL
      DELETE
        pt1
      FROM
        post_tags pt1
        INNER JOIN
          post_tags pt2
          ON
            pt1.post_id = pt2.post_id
            AND pt1.tag_id = pt2.tag_id
            AND pt1.id > pt2.id
      ;
    SQL

    add_column :post_tags, :discarded_at, :datetime
    add_index :post_tags, :discarded_at

    add_column :post_tags, :is_active, :boolean,
               as: 'discarded_at IS NULL', stored: true

    add_column :post_tags, :active_unique_key, :string,
               as: "CASE WHEN discarded_at IS NULL THEN CONCAT(post_id, ':', tag_id) ELSE NULL END",
               stored: true

    add_index :post_tags, :active_unique_key, unique: true, name: 'idx_post_tags_active_unique'

    add_index :post_tags, [:post_id, :discarded_at]
    add_index :post_tags, [:tag_id, :discarded_at]
  end

  def down
    raise ActiveRecord::IrreversibleMigration, '戻せません．'
  end
end
