class AddTagNameToTags < ActiveRecord::Migration[7.0]
  class Tag < ApplicationRecord
    self.table_name = 'tags'
  end

  class TagName < ApplicationRecord
    self.table_name = 'tag_names'
  end

  def up
    add_reference :tags, :tag_name, null: true, foreign_key: true, index: false, after: :id
    add_index :tags, :tag_name_id, unique: true

    Tag.find_each do |tag|
      name = tag.read_attribute(:name)
      tn = TagName.find_or_create_by!(name:) do |r|
        r.canonical_id = nil
      end
      tag.update_columns(tag_name_id: tn.id)
    end

    change_column_null :tags, :tag_name_id, false

    remove_column :tags, :name
  end

  def down
    add_column :tags, :name, :string, limit: 255, null: true, after: :id

    Tag.find_each do |tag|
      tag_name_id = tag.read_attribute(:tag_name_id)
      name = TagName.find(tag_name_id).read_attribute(:name)
      tag.update_columns(name:)
    end

    change_column_null :tags, :name, false

    remove_foreign_key :tags, column: :tag_name_id
    remove_index :tags, :tag_name_id
    remove_column :tags, :tag_name_id
  end
end
