"""AES-256-GCM symmetric encryption for SMS OTP codes stored in authorization_value."""
import os
import base64
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from src.core.config import settings


def _get_key() -> bytes:
    key_b64 = settings.AUTH_OTP_ENCRYPTION_KEY
    if not key_b64:
        raise ValueError("AUTH_OTP_ENCRYPTION_KEY is not configured")
    key = base64.b64decode(key_b64)
    if len(key) != 32:
        raise ValueError("AUTH_OTP_ENCRYPTION_KEY must decode to exactly 32 bytes")
    return key


def encrypt_otp(otp: str) -> str:
    """Encrypt OTP string → base64-encoded 'nonce||ciphertext'."""
    nonce = os.urandom(12)
    ct = AESGCM(_get_key()).encrypt(nonce, otp.encode(), None)
    return base64.b64encode(nonce + ct).decode()


def decrypt_otp(encrypted: str) -> str:
    """Decrypt base64-encoded 'nonce||ciphertext' → plaintext OTP."""
    raw = base64.b64decode(encrypted)
    nonce, ct = raw[:12], raw[12:]
    return AESGCM(_get_key()).decrypt(nonce, ct, None).decode()
