"""Request-level presence tracking.

LastSeenMiddleware stamps each authenticated user's Profile with the time of
their last request and the IP it came from, so an admin can see who is online,
when they were last seen, and from where. Writes are throttled to roughly once
per minute and use ``.update()`` so they never re-trigger ``Profile.save()``.
"""
from django.utils import timezone

from .models import Profile

# Don't write on every request — at most once per this many seconds per user.
_THROTTLE_SECONDS = 60


def _client_ip(request):
    """Best-effort client IP: first hop of X-Forwarded-For, else REMOTE_ADDR."""
    forwarded = request.META.get('HTTP_X_FORWARDED_FOR')
    if forwarded:
        return forwarded.split(',')[0].strip()
    return request.META.get('REMOTE_ADDR')


class LastSeenMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        user = getattr(request, 'user', None)
        if user is not None and user.is_authenticated:
            profile = getattr(user, 'profile', None)
            if profile is not None:
                now = timezone.now()
                if (profile.last_seen is None
                        or (now - profile.last_seen).total_seconds() > _THROTTLE_SECONDS):
                    # update() avoids re-running Profile.save() (and its uid/
                    # referral_code generation) on a hot path.
                    Profile.objects.filter(pk=profile.pk).update(
                        last_seen=now, last_ip=_client_ip(request))

        return response
