from .models import UserActivity

class UserActivityMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        # Record activity for non-static requests
        path = request.path
        if not path.startswith('/static/') and not path.startswith('/media/'):
            try:
                # Ensure session exists
                if not request.session.session_key:
                    request.session.create()
                session_key = request.session.session_key

                # Extract Client IP handling reverse proxies (Traefik / Nginx)
                x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
                if x_forwarded_for:
                    ip = x_forwarded_for.split(',')[0].strip()
                else:
                    ip = request.META.get('REMOTE_ADDR', '')

                user_agent = request.META.get('HTTP_USER_AGENT', '')[:245]
                user = request.user if request.user.is_authenticated else None
                guest_name = request.session.get('guest_name', '') or request.COOKIES.get('guest_display_name', '')

                if session_key:
                    UserActivity.objects.update_or_create(
                        session_key=session_key,
                        defaults={
                            'user': user,
                            'guest_name': guest_name if not user else '',
                            'ip_address': ip,
                            'user_agent': user_agent,
                            'last_path': path[:245],
                        }
                    )
            except Exception:
                pass

        return response
