"""
Middleware to ensure UserProfile exists for authenticated users.

This middleware automatically creates a UserProfile for any authenticated user
that doesn't have one, preventing AttributeError when accessing user.user_profile.
"""

from django.utils.deprecation import MiddlewareMixin
from appauthentication.models import UserProfile
import logging

logger = logging.getLogger(__name__)


class EnsureUserProfileMiddleware(MiddlewareMixin):
    """
    Middleware that ensures every authenticated user has a UserProfile.
    Creates one if it doesn't exist.
    """
    
    def process_request(self, request):
        """
        Check if authenticated user has profile, create if missing.
        """
        if request.user.is_authenticated:
            # Use hasattr to safely check for user_profile
            if not hasattr(request.user, 'user_profile'):
                try:
                    # Try to get existing profile first
                    try:
                        UserProfile.objects.get(user=request.user)
                    except UserProfile.DoesNotExist:
                        # Create new profile
                        profile = UserProfile.objects.create(user=request.user)
                        # Add default 'sponsor' role
                        profile.add_role('sponsor')
                        logger.info(f"Auto-created UserProfile for user: {request.user.username}")
                except Exception as e:
                    logger.error(f"Error auto-creating UserProfile for {request.user.username}: {e}")
        
        return None
