#!/usr/bin/env ruby -w
# frozen_string_literal: true

require 'declarative_policy'
require 'benchmark/ips'

Dir["./spec/support/policies/*.rb"].each { |f| require f }
Dir["./spec/support/models/*.rb"].each { |f| require f }

DeclarativePolicy.configure! do
  named_policy :global, GlobalPolicy

  name_transformation do |name|
    'ReadmePolicy' if name == 'Vehicle'
  end
end

cache = {}
valid_license = License[:valid]
country = Country.moderate
registration = Registration.new(number: 'xyz123', country: country)
driver = User.new(name: 'The driver', driving_license: valid_license)
owner = User.new(name: 'The Owner', trusted: [driver.name])
car = Vehicle.new(owner: owner, registration: registration)

raise 'Expected to drive' unless DeclarativePolicy.policy_for(driver, car).allowed?(:drive_vehicle)

branch = `git rev-parse --abbrev-ref HEAD`.chomp

Benchmark.ips do |x|
  x.report "cached - known ability - #{branch}" do
    DeclarativePolicy.policy_for(driver, car, cache: cache).allowed?(:drive_vehicle)
  end

  x.report "cached - unknown ability - #{branch}" do
    DeclarativePolicy.policy_for(driver, car, cache: cache).allowed?(:unknown_ability)
  end

  x.report "uncached - known ability - #{branch}" do
    DeclarativePolicy.policy_for(driver, car).allowed?(:drive_vehicle)
  end

  x.report "uncached - unknown ability - #{branch}" do
    DeclarativePolicy.policy_for(driver, car).allowed?(:unknown_ability)
  end

  x.compare!
  x.save! 'benchmarks/.repeated_invocation.bm-ips'
end
