module PayoutEntities
  class BulkInvitationPolicy < ApplicationPolicy
    def index?
      allowed?
    end

    def create?
      user_category_allowed?(@record.user_category.downcase)
    end

    def allowed?
      authorized_categories.any?
    end

    def authorized_categories
      [
        {
          permission: :payout_entities_bulk_invitation_0cpm,
          category: BulkInvitation::CATEGORY_0CPM
        },
        {
          permission: :payout_entities_bulk_invitation_affiliate,
          category: BulkInvitation::CATEGORY_AFFILIATE
        },
        {
          permission: :payout_entities_bulk_invitation_partner,
          category: BulkInvitation::CATEGORY_PARTNER
        }
      ]
        .select { |p| user.permitted?(BeefCake::Permission.for(p[:permission])) }
        .map { |p| p[:category] }
    end

    private

    def user_category_allowed?(category)
      user.permitted? BeefCake::Permission.for(
        ('payout_entities_bulk_invitation_' + category).to_sym
      )
    end
  end
end
