from cryptography.fernet import Fernet
from .. import settings


def _fernet():
    if not settings.ENCRYPTION_KEY:
        raise RuntimeError("ENCRYPTION_KEY not configured")
    return Fernet(
        settings.ENCRYPTION_KEY.encode()
        if isinstance(settings.ENCRYPTION_KEY, str)
        else settings.ENCRYPTION_KEY
    )


def encrypt_str(s: str | None) -> str | None:
    if not s:
        return None
    return _fernet().encrypt(s.encode()).decode()


def decrypt_str(s: str | None) -> str | None:
    if not s:
        return None
    return _fernet().decrypt(s.encode()).decode()
