require 'test_helper'

class DomainConstraintsTest < ActiveSupport::TestCase

  def setup
    ThreeScale::DevDomain.stubs(enabled?: false)
  end

  class BuyerDomainConstraintsTest < DomainConstraintsTest
    test 'buyer domain accepting all hostname' do
      request = mock
      ThreeScale.config.stubs(tenant_mode: 'developer')
      assert BuyerDomainConstraint.matches?(request)
    end

    test 'master domain is not a buyer domain' do
      ThreeScale.config.stubs(tenant_mode: 'multitenant')
      account = FactoryGirl.create(:simple_provider)
      request = mock
      request.expects(:host).returns(account.domain).at_least_once
      Account.stubs(master: account)
      refute BuyerDomainConstraint.matches?(request)
    end

    test 'multitenant accepting buyer domain' do
      ThreeScale.config.stubs(tenant_mode: 'multitenant')
      account = FactoryGirl.create(:simple_provider)
      request = mock
      request.expects(:host).returns(account.domain).at_least_once
      assert BuyerDomainConstraint.matches?(request)
    end

    test 'multitenant not recognizing a buyer domain' do
      ThreeScale.config.stubs(tenant_mode: 'multitenant')
      request = mock
      request.stubs(:host).returns('example.com')
      Account.expects(:exists?).with(domain: 'example.com').returns(false)
      refute BuyerDomainConstraint.matches?(request)
    end
  end

  class ProviderDomainConstraintTest < DomainConstraintsTest
      test 'single tenant, accepts all domains for provider' do
        ThreeScale.config.stubs(tenant_mode: 'provider')
      request = mock
      assert ProviderDomainConstraint.matches?(request)
    end

    test 'multitenant accepting provider domain' do
      ThreeScale.config.stubs(tenant_mode: 'multitenant')
      account = FactoryGirl.create(:simple_provider)
      request = mock
      request.expects(:host).returns(account.self_domain).at_least_once
      assert ProviderDomainConstraint.matches?(request)
    end

    test 'multitenant not recognizing a provider domain' do
      ThreeScale.config.stubs(tenant_mode: 'multitenant')
      request = mock
      request.stubs(:host).returns('admin.example.com')
      Account.expects(:exists?).with(self_domain: 'admin.example.com').returns(false)
      refute ProviderDomainConstraint.matches?(request)
    end
  end

  class MasterDomainConstraintTest < DomainConstraintsTest
    test 'master domain' do
      master = master_account
      request = mock
      request.expects(:host).returns(master.domain)
      assert MasterDomainConstraint.matches?(request)
    end
  end
end

