require 'bundler/setup'
gem 'activerecord'
require 'padrino-core/cli/rake'

PadrinoTasks.use(:database)
PadrinoTasks.use(:activerecord)
PadrinoTasks.init

def activerecord_below_5_2?
  ActiveRecord.version.release() < Gem::Version.new('5.2.0')
end

def activerecord_below_6?
  ActiveRecord.version.release() < Gem::Version.new('6.0')
end

def activerecord_below_7_1?
  ActiveRecord.version.release() < Gem::Version.new('7.1')
end

# v4.24
desc "Migrate the database in Rails way"
task(:db_migrate) do
  require 'active_record'
  require 'erb'
  db_yml_template = File.read('config/database.yml')
  db_yml_content = ERB.new(db_yml_template).result(binding)
  db_opts = YAML::load(db_yml_content)[ENV["RACK_ENV"] || "development"]
  ActiveRecord::Base.logger = Logger.new("log/migrate.log")
  ActiveRecord::Base.establish_connection(db_opts)
  if activerecord_below_5_2?
    ActiveRecord::Migrator.migrate('db/migrate')
  elsif activerecord_below_6?
    ActiveRecord::MigrationContext.new('db/migrate').migrate
  elsif activerecord_below_7_1?
    ActiveRecord::MigrationContext.new('db/migrate',  ActiveRecord::SchemaMigration).migrate
  else
    ActiveRecord::MigrationContext.new('db/migrate').migrate
  end
end