require 'test_helper'

class AccessTokenTest < ActiveSupport::TestCase

  def setup
    @token = FactoryGirl.build(:access_token, owner: nil)
  end

  def test_destroy_dependency
    @token.owner = member
    @token.save!

    member.destroy
    assert_raise(ActiveRecord::RecordNotFound) do
      @token.reload
    end
  end

  def test_non_public_scopes
    member.admin_sections = [:monitoring, :portal]
    member.save!
    @token.owner = member
    @token.save!

    Account.any_instance.expects(:provider_can_use?).with('cms_api').returns(false)
    assert_equal ['stats'], @token.available_scopes.values

    Account.any_instance.expects(:provider_can_use?).with('cms_api').returns(true)
    assert_equal ['cms', 'stats'], @token.available_scopes.values
  end

  def test_available_permissions
    assert_kind_of Hash, @token.available_permissions
  end

  def test_available_scopes
    @token.expects(:owner).returns(member).at_least_once
    assert_kind_of AccessToken::Scopes, @token.available_scopes
  end

  def test_available_scopes_user
    @token.expects(:owner).returns(member).at_least_once
    member.expects(:allowed_access_token_scopes).returns(AccessToken::Scopes.new([])).once

    @token.available_scopes
  end

  def test_scopes=
    @token.owner  = member
    @token.scopes = ['stats', 'cms', '', nil]
    @token.save!

    assert_equal ['stats', 'cms'], @token.scopes
  end

  def test_allowed_access_token_scopes
    member.admin_sections = []
    member.save

    assert_equal [], member.allowed_access_token_scopes.values

    member.admin_sections = [:partners]
    member.save

    assert_equal ['account_management'], member.allowed_access_token_scopes.values

    member.admin_sections = [:monitoring, :partners, :portal]
    member.save

    assert_equal ['cms', 'account_management', 'stats'],
                   member.allowed_access_token_scopes.values
  end

  def test_human_scopes
    assert Array, @token.human_scopes
  end

  private

  def member
    @member ||= FactoryGirl.build(:member, account: account)
  end

  def account
    @account ||= FactoryGirl.build_stubbed(:simple_provider)
  end
end
