from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from .models import Student

class MiniProgramUser:
    """
    A proxy user class to represent an authenticated Mini Program student
    """
    def __init__(self, student):
        self.student = student
        self.username = student.name or 'WeChat User'
        self.is_authenticated = True
        self.is_staff = False
        self.is_superuser = False
    
    def __str__(self):
        return self.username

class MiniProgramAuthentication(BaseAuthentication):
    """
    Custom Authentication for WeChat Mini Program
    Parses 'Bearer mock_token_{id}' and sets request.user to a proxy user
    """

    def authenticate(self, request):
        auth = request.headers.get('Authorization')
        if not auth or 'Bearer' not in auth:
            return None
        
        try:
            token_str = auth.split(' ')[1]
            if not token_str.startswith('mock_token_'):
                return None # Let other authenticators (like JWT) handle it
            
            try:
                student_id = int(token_str.split('_')[-1])
                student = Student.objects.get(id=student_id)
            except (ValueError, Student.DoesNotExist):
                raise AuthenticationFailed('Invalid mini-program token')
            
            # Create a proxy user
            user = MiniProgramUser(student)
            
            return (user, token_str)
            
        except AuthenticationFailed:
            raise
        except Exception:
            return None
