"""
Tenant-aware middleware for multi-tenancy
"""
from django.utils.deprecation import MiddlewareMixin


class TenantMiddleware(MiddlewareMixin):
    """
    Middleware that sets the current hospital context from the authenticated user.

    This middleware ensures that:
    - authenticated users have their tenant_hospital set from their profile
    - PX admins can switch between hospitals via session
    - All requests have tenant context available
    """

    def process_request(self, request):
        """Set tenant hospital context on each request."""
        if request.user and request.user.is_authenticated:
            # Store user's role for quick access
            request.user_roles = request.user.get_role_names()

            # PX Admins can switch hospitals via session
            if request.user.is_px_admin():
                hospital_id = request.session.get('selected_hospital_id')
                if hospital_id:
                    from apps.organizations.models import Hospital
                    try:
                        # Validate that the hospital exists
                        request.tenant_hospital = Hospital.objects.get(id=hospital_id)
                    except Hospital.DoesNotExist:
                        # Invalid hospital ID, fall back to default
                        request.tenant_hospital = None
                        # Clear invalid session data
                        request.session.pop('selected_hospital_id', None)
                else:
                    # No hospital selected yet
                    request.tenant_hospital = None
            else:
                # Non-PX Admin users use their assigned hospital
                request.tenant_hospital = request.user.hospital
        else:
            request.tenant_hospital = None
            request.user_roles = []

        return None
