"""
Crypto helpers for encrypting/decrypting secrets at rest.
"""

import logging
from typing import Optional
from cryptography.fernet import Fernet, InvalidToken

from app.core.config import settings

logger = logging.getLogger(__name__)


def _get_fernet() -> Fernet:
    if not settings.NEXTCLOUD_ENCRYPTION_KEY:
        raise ValueError("NEXTCLOUD_ENCRYPTION_KEY not configured")
    return Fernet(settings.NEXTCLOUD_ENCRYPTION_KEY.encode())


def encrypt_secret(value: str) -> str:
    fernet = _get_fernet()
    return fernet.encrypt(value.encode()).decode()


def decrypt_secret(value: str) -> Optional[str]:
    try:
        fernet = _get_fernet()
        return fernet.decrypt(value.encode()).decode()
    except (InvalidToken, ValueError) as exc:
        logger.error("❌ Nextcloud credential decryption failed: %s", exc)
        return None
