require 'debci'
require 'active_record'
require 'kaminari/core'
require 'kaminari/activerecord'

module Debci
  module DB
    def self.config
      @config ||= ENV['DATABASE_URL'] || Debci.config.database_url
    end

    def self.establish_connection
      ActiveRecord::Base.establish_connection(config)
    end

    def self.migrate(target_version = nil)
      migrations_path = File.join(File.dirname(__FILE__), 'db', 'migrations')
      ActiveRecord::Migration.verbose = !Debci.config.quiet
      if ActiveRecord.version.release >= Gem::Version.new('7.0')
        pool = ActiveRecord::Base.connection_pool
        migrations = ActiveRecord::MigrationContext.new(migrations_path).migrations
        ActiveRecord::Migrator.new(:up, migrations, pool.schema_migration, pool.internal_metadata).migrate
      elsif ActiveRecord.version.release >= Gem::Version.new('6.0')
        # ActiveRecord 6+
        ActiveRecord::MigrationContext.new(migrations_path, ActiveRecord::SchemaMigration).migrate(target_version)
      else
        # ActiveRecord 5.2
        ActiveRecord::MigrationContext.new(migrations_path).migrate(target_version)
      end
    end
    version_isnewer = ActiveRecord.version.release < Gem::Version.new('5.1.0')
    LEGACY_MIGRATION = if version_isnewer
                         ActiveRecord::Migration
                       else
                         ActiveRecord::Migration[4.2]
                       end
  end
end

if ActiveRecord.version.release < Gem::Version.new('7.0')
  class ActiveRecord::Base
    def self.serialize(field, **options)
      type = options.delete(:type)
      super(field, type, **options)
    end
  end
end

Debci::DB.establish_connection
