import rules


def has_organization_role(user, org, roles):
    from servala.core.models import Organization

    if not isinstance(org, Organization):
        return False
    memberships = org.memberships.all().filter(user=user)
    if roles:
        memberships = memberships.filter(role__in=roles)
    return memberships.exists()


@rules.predicate
def is_organization_owner(user, obj):
    from servala.core.models.organization import OrganizationRole

    if hasattr(obj, "organization"):
        org = obj.organization
    else:
        org = obj
    return has_organization_role(user, org, [OrganizationRole.OWNER])


@rules.predicate
def is_organization_admin(user, obj):
    from servala.core.models.organization import OrganizationRole

    if hasattr(obj, "organization"):
        org = obj.organization
    else:
        org = obj
    return has_organization_role(
        user, org, [OrganizationRole.OWNER, OrganizationRole.ADMIN]
    )


@rules.predicate
def is_organization_member(user, obj):
    if hasattr(obj, "organization"):
        org = obj.organization
    else:
        org = obj
    return has_organization_role(user, org, None)


rules.add_perm("core", rules.is_staff)
