if ENV["COVERAGE"] != "no"
  begin
    require 'simplecov'
    RSpec.configure do |config|
      unless config.files_to_run.one?
        SimpleCov.start do
          minimum_coverage(93)
          track_files('lib/**/*.rb')
          add_filter(/migrations/)
          add_filter(/spec/)
        end
      end
    end
  rescue LoadError
    $stderr.puts "W: simplecov not installed, not checking test coverage"
  end
end

ENV['DATABASE_URL'] ||= 'sqlite3::memory:'
ENV['RACK_ENV'] = 'test'

require 'fileutils'
require 'rack/test'
require 'tmpdir'
require 'yaml'
require 'debci/db'
require 'debci/job'
require 'debci/app'

if Gem::Specification.find_by_name("bullet").version >= Gem::Version.new("7")
  require 'bullet'
  module Debci
    class App
      configure do
        Bullet.enable = true
        Bullet.bullet_logger = true
        Bullet.raise = true
        use Bullet::Rack
      end
    end
  end
end

require 'database_cleaner'
require 'omniauth'
DatabaseCleaner.allow_remote_database_url = true
DatabaseCleaner.strategy = :transaction

Debci.config.backend = 'fake'
Debci.config.backend_list = ['fake', 'lxc', 'incus-lxc', 'qemu']
Debci.config.quiet = true
Debci::DB.migrate

arch = `dpkg --print-architecture`.strip

RSpec.shared_context 'tmpdir' do
  let(:arch) { arch }
  let(:tmpdir) { Dir.mktmpdir("debci-tests-") }
  after(:each) { FileUtils.rm_rf(tmpdir) }
end

RSpec.shared_context 'no-rabbitmq' do
  before(:each) do
    allow_any_instance_of(Debci::Job).to receive(:enqueue)
  end
end

root = File.join(File.dirname(__FILE__), '..')
Dir.chdir(root) do
  system('make static')
end

RSpec.configure do |config|
  config.include_context 'tmpdir'
  config.before(:each) do
    allow(Debci).to receive(:warn)
    allow_any_instance_of(Debci::Config).to receive(:arch_list).and_return([arch])
    allow_any_instance_of(Debci::Config).to receive(:suite_list).and_return(['unstable', 'testing'])
    allow_any_instance_of(Debci::Config).to receive(:data_basedir).and_return(File.join(tmpdir, '/data'))
    allow_any_instance_of(Debci::Config).to receive(:html_dir).and_return(File.join(tmpdir, '/data/.html'))
  end
  config.before(:each) do
    DatabaseCleaner.start
  end
  config.after(:each) do
    DatabaseCleaner.clean
  end
end

OmniAuth.config.test_mode = true

# module for logging in in tests. Note that for using this, the test scenario
# needs to have the self service app mounted at /user, besides the app being
# tested.
module WebAppHelper
  include Rack::Test::Methods

  def fake_login(username)
    env("rack.session", { :user_id => Debci::User.create!(username: username).id })
  end

  def login(username, uid = nil)
    uid ||= username.hash % 1000
    OmniAuth.config.mock_auth[:gitlab] = OmniAuth::AuthHash.new({
      provider: 'gitlab',
      uid: uid,
      info: OmniAuth::AuthHash::InfoHash.new({ username: username })
    })
    get '/user/auth/gitlab/callback'
  end

  def logout
    env("rack.session", {})
  end
end
