class MigrateAndRemoveSoftwareImageId < ActiveRecord::Migration[8.0]
  def up
    Software.unscoped.where.not(image_id: nil).find_each do |sw|
      SoftwareImage.create!(
        software_id: sw.id,
        image_id:    sw.image_id,
        is_default:  true,
        position:    0
      )
    end

    remove_foreign_key :softwares, :images
    remove_column :softwares, :image_id
  end

  def down
    add_column :softwares, :image_id, :bigint
    add_foreign_key :softwares, :images

    SoftwareImage.where(is_default: true).find_each do |si|
      Software.unscoped.where(id: si.software_id).update_all(image_id: si.image_id)
    end
  end
end
