class AddVersionNoToTags < ActiveRecord::Migration[8.0]
  def up
    add_column :tags, :version_no, :integer

    execute <<~SQL
      UPDATE
        tags
      SET
        version_no = (
          CASE category
          WHEN 'nico' THEN
            (SELECT
               MAX(version_no)
             FROM
               nico_tag_versions
             WHERE
               tag_id = tags.id)
          ELSE
            (SELECT
               MAX(version_no)
             FROM
               tag_versions
             WHERE
               tag_id = tags.id)
          END)
    SQL

    change_column_null :tags, :version_no, false

    add_check_constraint :tags, 'version_no > 0', name: 'chk_tags_version_no_positive'
  end

  def down
    remove_check_constraint :tags, name: 'chk_tags_version_no_positive'
    remove_column :tags, :version_no
  end
end
