from rest_framework.permissions import BasePermission


class IsCEO(BasePermission):
    def has_permission(self, request, view):
        return request.user.is_authenticated and request.user.has_role('CEO')


class IsPM(BasePermission):
    def has_permission(self, request, view):
        return request.user.is_authenticated and request.user.has_role('CEO', 'PM')


class IsTL(BasePermission):
    def has_permission(self, request, view):
        return request.user.is_authenticated and request.user.has_role('CEO', 'PM', 'TL')


class IsManagement(BasePermission):
    """CEO, PM, or TL"""
    def has_permission(self, request, view):
        return request.user.is_authenticated and request.user.has_role('CEO', 'PM', 'TL')


class IsBDSales(BasePermission):
    def has_permission(self, request, view):
        return request.user.is_authenticated and request.user.has_role('CEO', 'PM', 'BD')


class IsFinance(BasePermission):
    def has_permission(self, request, view):
        return request.user.is_authenticated and request.user.has_role('CEO', 'Finance')


class IsHRAdmin(BasePermission):
    def has_permission(self, request, view):
        return request.user.is_authenticated and request.user.has_role('CEO', 'HR')


class CanManageUsers(BasePermission):
    def has_permission(self, request, view):
        return request.user.is_authenticated and request.user.has_role('CEO', 'HR')


class CanViewFinance(BasePermission):
    def has_permission(self, request, view):
        return request.user.is_authenticated and request.user.has_role('CEO', 'Finance', 'PM')


class CanManageLeads(BasePermission):
    def has_permission(self, request, view):
        return request.user.is_authenticated and request.user.has_role('CEO', 'PM', 'BD')


class CanApprove(BasePermission):
    def has_permission(self, request, view):
        return request.user.is_authenticated and request.user.has_role('CEO', 'PM', 'TL')


class IsOwnerOrManagement(BasePermission):
    """Object-level: user is the object owner or is management"""
    def has_object_permission(self, request, view, obj):
        if request.user.has_role('CEO', 'PM', 'TL'):
            return True
        if hasattr(obj, 'user'):
            return obj.user == request.user
        if hasattr(obj, 'assigned_to'):
            return obj.assigned_to == request.user
        if hasattr(obj, 'created_by'):
            return obj.created_by == request.user
        return False
