class AddTagNameToWikiPages < ActiveRecord::Migration[7.0]
  class WikiPage < ApplicationRecord
    self.table_name = 'wiki_pages'
  end

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

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

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

    change_column_null :wiki_pages, :tag_name_id, false

    remove_column :wiki_pages, :title
  end

  def down
    add_column :wiki_pages, :title, :string, limit: 255, null: true, after: :id

    WikiPage.find_each do |page|
      tag_name_id = page.read_attribute(:tag_name_id)
      title = TagName.find(tag_name_id).read_attribute(:name)
      page.update_columns(title:)
    end

    change_column_null :wiki_pages, :title, false

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