# ============================================================
# ADDITIVE: encryption of stored SMTP passwords (Fernet = AES-128-CBC + HMAC).
# Key: settings.COMPANY_SMTP_ENCRYPTION_KEY (a Fernet key, set it in the environment in production),
#      otherwise derived from SECRET_KEY.  If the key changes, old passwords cannot be decrypted and the
#      configuration is reported as "password must be re-entered" instead of crashing.
# ============================================================
import base64
import hashlib

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured


def _fernet():
    try:
        from cryptography.fernet import Fernet
    except ImportError:                                           # pragma: no cover
        raise ImproperlyConfigured("Storing SMTP passwords needs the 'cryptography' package: pip install cryptography")
    key = getattr(settings, "COMPANY_SMTP_ENCRYPTION_KEY", None)
    if not key:
        key = base64.urlsafe_b64encode(hashlib.sha256(("hrnexus-smtp|" + settings.SECRET_KEY).encode()).digest())
    return Fernet(key if isinstance(key, bytes) else key.encode())


def encrypt(plain):
    return _fernet().encrypt(plain.encode("utf-8")).decode("ascii") if plain else ""


def decrypt(token):
    """Plain password, '' when none is stored, None when it cannot be decrypted (key changed / corrupt)."""
    if not token:
        return ""
    try:
        return _fernet().decrypt(token.encode("ascii")).decode("utf-8")
    except Exception:
        return None
