import datetime
import jwt
from django.conf import settings

def generate_access_token(user):
    access_token_payload = {
        'user_id': user.id,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(days=10),
        'iat': datetime.datetime.utcnow(),
    }
    access_token = jwt.encode(access_token_payload, settings.SECRET_KEY, algorithm='HS256')
    # access_token = str(access_token,'utf-8')
    return access_token


def generate_refresh_token(user):
    refresh_token_payload = {
        'user_id': user.id,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(days=10),
        'iat': datetime.datetime.utcnow()
    }

    refresh_token = jwt.encode(refresh_token_payload, settings.SECRET_KEY, algorithm='HS256', lifetime=datetime.timedelta(days=10))
    # refresh_token = str(refresh_token,'utf-8')
    return refresh_token



def verify_token(request):
    authorization_header = request.headers.get('Authorization')
    if not authorization_header:
        return None
    try:
        access_token = authorization_header.split(' ')[1]
        payload = jwt.decode(access_token, settings.SECRET_KEY, algorithms='HS256')
        return (payload['user_id'])
    except jwt.ExpiredSignatureError:
        return None
    except jwt.exceptions.InvalidSignatureError:
        return None
    except IndexError:
        return None