import hmac
import hashlib

from app.config import settings

_NAMESPACE = "surat-verify-v1"


def sign_surat(surat_id: int, no_surat: str) -> str:
    """HMAC signature binding a surat's id + no_surat, used as the QR token.
    Recomputed on every response — not stored — so it always reflects the
    current no_surat (regenerated no_surat invalidates old QR codes/links).
    """
    msg = f"{_NAMESPACE}:{surat_id}:{no_surat}".encode()
    return hmac.new(settings.JWT_SECRET.encode(), msg, hashlib.sha256).hexdigest()[:20]


def verify_sig(surat_id: int, no_surat: str, sig: str) -> bool:
    expected = sign_surat(surat_id, no_surat)
    return hmac.compare_digest(expected, sig)
