class RadHocQueryAuthorizer < ApplicationAuthorizer
  RESTRICTED_COLS = {
      "users.pay_rate"              => lambda { |m| m.security_group.admin },
      "users.encrypted_password"    => lambda { |m| false },
      "users.reset_password_token"  => lambda { |m| false },
      "charges.bill_rate"           => lambda { |m| m.security_group.admin },
      "charges.bill_amount"         => lambda { |m| m.security_group.admin },
  }

  # class rules
  def self.creatable_by?(user)
    true
  end

  def self.readable_by?(user)
    true
  end

  def self.updatable_by?(user)
    true
  end

  def self.deletable_by?(user)
    true
  end

  # instance rules

  def readable_by?(member)
    class_auth = resource.authorized_models(member)

    attr_auth = resource.all_cols.reduce(true) do |readable, col|
      column_name = [col.relation.name, col.name].join('.')
      default_to_readable = Proc.new { true }
      readable && RESTRICTED_COLS.fetch(column_name, default_to_readable).call(member)
    end

    class_auth && attr_auth && visible(member)
  end

  def updatable_by?(member)
    resource.readable_by?(member) && (resource.member == member || member.security_group.admin)
  end

  def deletable_by?(member)
    resource.member == member || member.security_group.admin
  end

  private

    def visible(member)
      return !resource.only_me? || resource.member == member
    end

end
