"""Fernet encryption helpers for WhatsApp access tokens.

Tokens are encrypted at rest with a versioned key so key rotation
is possible without re-encrypting all rows in a single migration.
"""

import os

from cryptography.fernet import Fernet

# Active encryption key loaded from env. Absence means encrypt/decrypt
# will fail at call time, not import time, so tests can import without it.
_KEY_ENV = "WHATSAPP_TOKEN_ENCRYPTION_KEY"


def _get_fernet(key: str | None = None) -> Fernet:
    """Return a Fernet instance for the given or active key."""
    raw = key or os.environ.get(_KEY_ENV, "")
    if not raw:
        raise RuntimeError(f"{_KEY_ENV} is not set. Cannot encrypt/decrypt WhatsApp tokens.")
    return Fernet(raw.encode() if isinstance(raw, str) else raw)


def encrypt_token(plaintext: str, *, key: str | None = None) -> bytes:
    """Encrypt a plaintext access token. Returns Fernet ciphertext bytes."""
    return _get_fernet(key).encrypt(plaintext.encode("utf-8"))


def decrypt_token(ciphertext: bytes, *, key: str | None = None) -> str:
    """Decrypt a Fernet-encrypted access token. Returns plaintext string.

    Raises ``cryptography.fernet.InvalidToken`` on wrong key or tampered data.
    """
    return _get_fernet(key).decrypt(ciphertext).decode("utf-8")
