import jwt
from django.conf import settings
from django.contrib.auth.models import User
from rest_framework import authentication, exceptions


class JWTAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        header = request.headers.get('Authorization', '')
        if not header.startswith('Bearer '):
            return None
        try:
            payload = jwt.decode(header[7:], settings.SECRET_KEY, algorithms=['HS256'])
            user = User.objects.get(id=payload['user_id'], is_active=True)
        except (jwt.PyJWTError, KeyError, User.DoesNotExist):
            raise exceptions.AuthenticationFailed('Invalid or expired token.')
        return user, payload


def issue_token(user):
    return jwt.encode({'user_id': user.id, 'email': user.email}, settings.SECRET_KEY, algorithm='HS256')
