require 'test_helper'

class SiteAccountSupportTest < ActiveSupport::TestCase

  class Params
    attr_accessor :request

    class << self
      def before_filter(*args); end

      def helper_method(*args)
        public *args
      end
    end

    include SiteAccountSupport
  end

  test 'scopes provider key search by domain' do
    p1 = FactoryGirl.create(:provider_account)
    p2 = FactoryGirl.create(:provider_account)

    object = Params.new
    object.request = mock(host: p2.self_domain, params: { provider_key: p2.api_key })

    assert_equal p2, object.site_account

    object = Params.new
    object.request = mock(host: p2.self_domain, params: { provider_key: p1.api_key })

    assert_raise Backend::ProviderKeyInvalid do
      refute object.site_account
    end
  end

  test 'raises record not found' do
    assert_raises ActiveRecord::RecordNotFound do
      Params.new.domain_account
    end
  end

  class SingleTenantTest < ActiveSupport::TestCase
    def setup
      master = master_account
      master.update_columns(provider: false)
    end

    test 'site_account finds the first provider on developer portal wildcard' do
      ThreeScale.config.stubs(tenant_mode: 'developer'.freeze)

      providers = FactoryGirl.create_list(:provider_account, 3)
      p1 = providers.first

      object = Params.new
      object.request = mock(params: {})
      assert_equal p1, object.site_account
    end

    test 'site_account is master on admin portal wildcard' do
      ThreeScale.config.stubs(tenant_mode: 'provider'.freeze)
      FactoryGirl.create_list(:provider_account, 3)

      object = Params.new
      object.request = mock(params: {})
      assert_equal master_account, object.site_account
    end

    test 'domain_account finds the first provider on developer portal wildcard' do
      ThreeScale.config.stubs(tenant_mode: 'developer'.freeze)

      providers = FactoryGirl.create_list(:provider_account, 3)
      p1 = providers.first

      object = Params.new
      object.request = mock
      assert_equal p1, object.domain_account
    end

    test 'domain_account is first provider on admin portal wildcard' do
      ThreeScale.config.stubs(tenant_mode: 'provider'.freeze)
      providers = FactoryGirl.create_list(:provider_account, 3)
      p1 = providers.first

      object = Params.new
      object.request = mock
      assert_equal p1, object.domain_account
    end
  end
end
