from django.contrib.auth.backends import ModelBackend


class CompanyUserBackend(ModelBackend):
    def get_user_permissions(self, user_obj, obj=None):
        if not user_obj.is_active or user_obj.is_anonymous:
            return set()

        if user_obj.is_superuser:
            return super().get_user_permissions(user_obj, obj)

        perms = super().get_user_permissions(user_obj, obj)
        if user_obj.company and user_obj.company.is_client:
            # Filter permissions based on client company context
            perms = {p for p in perms if p.startswith('accounts.client_')}
        return perms