require 'torque-postgresql'
require 'database_cleaner'
require 'factory_bot'
require 'dotenv'
require 'faker'
require 'rspec'

begin
  require 'debug/prelude'
rescue LoadError
  # No debugger available, skip
end

Dotenv.load

ActiveRecord::Base.establish_connection(ENV['DATABASE_URL'] || {
  adapter: 'postgresql',
  username: 'travis',
  port: 5433,
})

cache = ActiveRecord::Base.connection.schema_cache
cleaner = ->() do
  cache.instance_variable_set(:@inheritance_loaded, false)
  cache.instance_variable_set(:@inheritance_dependencies, {})
  cache.instance_variable_set(:@inheritance_associations, {})
end

# Load all the files that are optional and managed by Railtie
require_relative 'initialize'

# This needs to come after loading all optional features
require_relative 'schema'
Dir.glob(File.join('spec', '{models,factories,mocks}', '**', '*.rb')) do |file|
  require file[5..-4]
end

cleaner.call
I18n.load_path << Pathname.pwd.join('spec', 'en.yml')
RSpec.configure do |config|
  config.extend Mocks::CreateTable
  config.include Mocks::CacheQuery
  config.include FactoryBot::Syntax::Methods

  config.formatter = :documentation
  config.color     = true
  config.tty       = true

  # Handles acton before rspec initialize
  config.before(:suite) do
    Torque::PostgreSQL.config.schemas.whitelist << 'internal'
    ActiveSupport::Deprecation.try(:silenced=, true)
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

  config.before(:each) do
    cleaner.call
  end
end
