require 'rails_helper'

RSpec.describe Dunlop::AuthorizationHelper, type: :helper do
  subject { helper }
  describe '#has_permission_of_type' do
    it "returns wether a permission exists" do
      user = create :user, role_names: ['read-adapter-epots', 'manage-model-epots/work-order']
      helper.has_permission_of_type('adapter', user).should be true
      helper.has_permission_of_type('class',   user).should be false
    end

    it 'returns always true for admin users' do
      user = create :admin
      helper.has_permission_of_type('adapter', user).should be true
    end
  end

  describe '#any_permission_starts_with' do
    it 'matches as a whole' do
      user = create :user, role_names: ['read-adapter-epots', 'manage-model-epots/source-file']
      helper.any_permission_starts_with('epots/source-file', user).should be true
      helper.any_permission_starts_with('panda', user).should be false
    end

    it 'matches for larger paths but not part of it' do
      user = create :user, role_names: ['manage-model-epots/source-file/work-order', 'read-model-epots/source-file/han-planning', 'read-model-different-start-epots/source-file']
      helper.any_permission_starts_with('epots/source-file', user).should be true
    end

    it 'does not get confused when expression is part of the target' do
      user = create :user, role_names: ['read-model-different-start-epots/source-file']
      helper.any_permission_starts_with('epots/source-file', user).should be false
    end

    it 'returns always true for admin users' do
      user = create :admin
      helper.any_permission_starts_with('epots/source-file', user).should be true
    end

    it 'supports multiple' do
      user = create :user, role_names: ['manage-model-epots/source-file']
      helper.any_permission_starts_with(['blabla', 'epots/source-file'], user).should be true
      helper.any_permission_starts_with(['blabla', 'epots/target-file'], user).should be false
    end
  end
end
