from rest_framework.permissions import BasePermission

from apps.accounts.models import Organization

def get_organization_from_object(obj):
    if isinstance(obj, Organization):
        return obj

    organization = getattr(obj, 'organization', None)
    if isinstance(organization, Organization):
        return organization

    role = getattr(obj, 'role', None)
    organization = getattr(role, 'organization', None)
    if isinstance(organization, Organization):
        return organization

    return None

def can_manage_organization(user, organization):
    if organization is None:
        return False

    is_owner = organization.owner.id == user.id
    is_member_manager = bool(user.is_manager) and organization.members.filter(id=user.id).exists()
    return is_owner or is_member_manager

class IsOrganizationOwnerOrMember(BasePermission):
    def has_object_permission(self, request, view, obj):
        if not isinstance(obj, Organization):
            return False
        return request.user.is_member_of(obj) or request.user.is_owner_of(obj)

class CanManageOrganization(BasePermission):
    def has_object_permission(self, request, view, obj):
        organization = get_organization_from_object(obj)
        return can_manage_organization(request.user, organization)
