"""Authorization scoping.

Each user only sees and edits the assets they are authorised to. A brand-new
individual starts empty — JM3 is their companion for their own trees, not a
window onto everyone else's data.

  jm3_admin / superuser   -> all assets (the platform view)
  org_admin / teacher     -> their organization's assets
  everyone else           -> assets they registered or own
"""

from .models import Asset


def visible_assets(user):
    if not user.is_authenticated:
        return Asset.objects.none()
    prof = getattr(user, "profile", None)
    role = prof.role if prof else "student"

    if user.is_superuser or role == "jm3_admin":
        return Asset.objects.all()

    if role in ("org_admin", "teacher") and prof and prof.organization_id:
        return Asset.objects.filter(organization_id=prof.organization_id)

    # Individuals (student / farmer / nursery_manager / community): their own.
    return Asset.objects.filter(registered_by=user)
