"""WhiteNoise subclass that also serves MEDIA_ROOT under MEDIA_URL.

WhiteNoise's official position is that it's intended for static files. For a
bootstrap deployment behind a single WSGI process this is acceptable; revisit
when traffic warrants Apache/nginx serving uploads directly.

SECURITY: serving MEDIA_ROOT this way applies NO authentication and NO tenant
check — every uploaded file is world-readable to anyone with the URL, and no
upload_to path carries an organization prefix, so one tenant's HR contracts and
bank statements sit in the same flat directory as another's. Deployments that
have migrated their clients to the authorizing download view
(apps.core.media_views.serve_media) set MEDIA_SERVE_UNAUTHENTICATED=False to
turn this off; the setting exists because the two deployments share this
codebase and cannot cut over on the same day.
"""

from django.conf import settings
from whitenoise.middleware import WhiteNoiseMiddleware


class WhiteNoiseWithMedia(WhiteNoiseMiddleware):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not getattr(settings, "MEDIA_SERVE_UNAUTHENTICATED", True):
            return
        if settings.MEDIA_ROOT and settings.MEDIA_URL:
            self.add_files(settings.MEDIA_ROOT, prefix=settings.MEDIA_URL)
