from apps.core.visibility_registry import VISIBILITY_MAP_BY_ORG_KEY


def apply_visibility_filter_by_org_type(queryset, org):
    """
    Dynamically filter queryset based on user's organization type and model.
    """

    if not org:
        return queryset.none()

    model_name = queryset.model.__name__.lower()

    if model_name not in VISIBILITY_MAP_BY_ORG_KEY:
        return queryset

    org_type_key = getattr(org.type, 'key', None)
    visibility_field = VISIBILITY_MAP_BY_ORG_KEY[model_name].get(org_type_key)

    if visibility_field is None:
        return queryset

    filter_kwargs = {f"{visibility_field}": org}
    return queryset.filter(**filter_kwargs)
