class AddAccountToUsers < ActiveRecord::Migration[5.2]
  def up
    add_reference :users, :account, foreign_key: true
    migrate_data_up
    remove_column :users, :team_name, :string
  end

  def down
    add_column :users, :team_name, :string
    migrate_user_data_down

    remove_reference :users, :account
    migrate_account_data_down
  end

  private

  def migrate_data_up
    say "Creating Accounts.."

    User.find_each do |user|
      account = Account.new(name: user.team_name.titleize, slug: user.team_name)
      user.update!(account: account)
    end

    say "Done."
  end

  def migrate_user_data_down
    say "Updating Users.."

    User.find_each do |user|
      user.update!(team_name: user.account.slug)
    end

    say "Done."
  end

  def migrate_account_data_down
    say "Destroying Accounts.."

    Account.delete_all

    say "Done."
  end

end
