"""Shared test helpers (e.g. make_init_data for Telegram auth tests)."""

import hashlib
import hmac
import json
from urllib.parse import quote, unquote


def make_init_data(
    user: dict | None,
    bot_token: str,
    auth_date: int | None = None,
) -> str:
    """Build initData string with valid HMAC for testing."""
    params = {}
    if user is not None:
        params["user"] = quote(json.dumps(user))
    if auth_date is not None:
        params["auth_date"] = str(auth_date)
    pairs = sorted(params.items())
    data_string = "\n".join(f"{k}={unquote(v)}" for k, v in pairs)
    secret_key = hmac.new(
        b"WebAppData",
        msg=bot_token.encode(),
        digestmod=hashlib.sha256,
    ).digest()
    computed = hmac.new(
        secret_key,
        msg=data_string.encode(),
        digestmod=hashlib.sha256,
    ).hexdigest()
    params["hash"] = computed
    return "&".join(f"{k}={v}" for k, v in sorted(params.items()))
