class AddEncryptedPersonSsnToAppearanceReleases < ActiveRecord::Migration[5.2]
  def up
    add_column :appearance_releases, :encrypted_person_ssn, :string
    add_column :appearance_releases, :encrypted_person_ssn_iv, :string

    migrate_data_up!

    remove_column :appearance_releases, :person_ssn, :string
  end

  def down
    add_column :appearance_releases, :person_ssn, :string

    migrate_data_down!

    remove_column :appearance_releases, :encrypted_person_ssn
    remove_column :appearance_releases, :encrypted_person_ssn_iv
  end

  private

  def migrate_data_up!
    say "Encrypting person SSNs..."

    AppearanceRelease.find_each do |appearance_release|
      # Access the value of the attribute directly using hash syntax then use the accessor to encrypt it
      appearance_release.update!(person_ssn: appearance_release[:person_ssn])
    end

    say "Done."
  end

  def migrate_data_down!
    say "Decrypting person SSNs..."

    AppearanceRelease.find_each do |appearance_release|
      appearance_release[:person_ssn] = appearance_release.person_ssn 
      appearance_release.save!
    end

    say "Done."
  end
end
