module BuyerDomainConstraint
  module_function

  def matches?(request)
    request.extend(ThreeScale::DevDomain::Request) if ThreeScale::DevDomain.enabled?
    if ThreeScale.likely_multitenant?
      Account.exists?(:domain => request.host) && !MasterDomainConstraint.matches?(request)
    else
      ThreeScale.tenant_mode.developer?
    end
  end
end

class DomainConstraint
  def initialize(domain)
    @domain = domain
  end

  def matches?(request)
    request.host == @domain
  end
end

module ProviderDomainConstraint
  module_function

  def matches?(request)
    request.extend(ThreeScale::DevDomain::Request) if ThreeScale::DevDomain.enabled?
    if ThreeScale.likely_multitenant?
      Account.exists?(:self_domain => request.host)
    else
      ThreeScale.tenant_mode.provider?
    end
  end
end

module MasterDomainConstraint
  module_function

  def matches?(request)
    request.extend(ThreeScale::DevDomain::Request) if ThreeScale::DevDomain.enabled?
    master = Account.master
    master.admin_domain == request.host or master.domain == request.host
  end
end

module MasterOrProviderDomainConstraints
  module_function

  def matches?(request)
    ProviderDomainConstraint.matches?(request) || MasterDomainConstraint.matches?(request)
  end
end

module LoggedInConstraint
  module_function

  def matches?(request)
    AuthenticatedSystem::Request.new(request).authenticated?
  end
end
