from rest_framework.permissions import BasePermission


class IsSuperAdmin(BasePermission):
    """超级管理员：is_staff=True 且 team=NULL"""
    def has_permission(self, request, view):
        return (
            request.user
            and request.user.is_authenticated
            and request.user.is_staff
            and request.user.team is None
        )


class IsTeamAdmin(BasePermission):
    """团队管理员：is_team_admin=True 且 team≠NULL"""
    def has_permission(self, request, view):
        return (
            request.user
            and request.user.is_authenticated
            and request.user.is_team_admin
            and request.user.team is not None
        )


class IsTeamAdminOrSuperAdmin(BasePermission):
    """团队管理员或超级管理员"""
    def has_permission(self, request, view):
        if not (request.user and request.user.is_authenticated):
            return False
        if request.user.is_staff and request.user.team is None:
            return True
        if request.user.is_team_admin and request.user.team is not None:
            return True
        return False


class IsTeamMember(BasePermission):
    """团队成员（含团管）：team≠NULL"""
    def has_permission(self, request, view):
        return (
            request.user
            and request.user.is_authenticated
            and request.user.team is not None
        )


class IsSuperAdminOrObserver(BasePermission):
    """超级管理员，或被标记为观察者的团队管理员（可查看全局内容资产）。"""
    def has_permission(self, request, view):
        u = request.user
        if not (u and u.is_authenticated):
            return False
        # 超管
        if u.is_staff and u.team is None:
            return True
        # 观察者团管
        if u.is_team_admin and u.team is not None and getattr(u, 'is_observer', False):
            return True
        return False
