# app_admin/authentication.py
from rest_framework.authentication import BaseAuthentication, get_authorization_header
from rest_framework.exceptions import AuthenticationFailed
from app_admin.models import AdminToken

class AdminTokenAuthentication(BaseAuthentication):
    def authenticate(self, request):
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != b'bearer':
            return None

        if len(auth) != 2:
            raise AuthenticationFailed('Ungültiger Authorization-Header.')

        raw_token = auth[1].decode()
        token_hash = AdminToken.hash_token(raw_token)  # ← eingehenden Token hashen

        try:
            token = AdminToken.objects.select_related('user').get(key_hash=token_hash)
        except AdminToken.DoesNotExist:
            raise AuthenticationFailed('Ungültiger Token.')

        return (token.user, token)
    
    def authenticate_header(self, request):
        return 'Bearer'