import base64
from datetime import datetime

import structlog
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
from django.conf import settings

logger = structlog.get_logger(__name__)

CIPHER_TRANSFORMATION = "RSA/ECB/PKCS1Padding"


def create_token(user_id: str):
    try:
        token = (
            f"user:{user_id};system:{settings.EDONIQ_ENV};date:"
            + str(int(datetime.now().timestamp()))
            + ";"
        )

        encrypted = _encrypt_message(
            token, settings.EDONIQ_CERTIFICATE.replace("\\n", "\n")
        )
        return str(base64.b64encode(encrypted), "utf-8")

    except Exception as e:
        logger.debug(
            "get_edoniq_test_fail",
            label="edoniq_test_api",
            error=e,
        )


def _encrypt_message(token: str, key: str):
    key = RSA.import_key(key)
    plainbytes = token.encode("utf-8")
    cipherbytes = _encrypt(plainbytes, key)
    encrypted_token = base64.b64encode(cipherbytes)
    return encrypted_token


def _encrypt(token, key):
    cipher = PKCS1_v1_5.new(key)
    return cipher.encrypt(token)
