import pytest
from core.encryption import encrypt_string, decrypt_string
from infrastructure.telegram.service import TelegramApiService
from infrastructure.telegram.webhook import (
    generate_webhook_secret,
    hash_webhook_secret,
    verify_webhook_secret,
)


@pytest.mark.asyncio
async def test_bot_token_validation_with_getme():
    token = "123456789:TEST_TOKEN_ALPHA"
    TelegramApiService.register_mock_bot(
        token=token,
        username="alpha_test_bot",
        first_name="Alpha Bot",
    )

    info = await TelegramApiService.validate_token(token)
    assert info["username"] == "alpha_test_bot"
    assert info["is_bot"] is True


def test_bot_token_encryption_and_decryption():
    raw_token = "987654321:AAE_SECRET_TELEGRAM_TOKEN_XYZ"
    encrypted_payload, key_version = encrypt_string(raw_token)

    assert encrypted_payload != raw_token
    assert "SECRET" not in encrypted_payload

    decrypted = decrypt_string(encrypted_payload, key_version)
    assert decrypted == raw_token


def test_webhook_secret_generation_and_verification():
    secret = generate_webhook_secret()
    assert len(secret) >= 32

    secret_hash = hash_webhook_secret(secret)
    assert secret_hash != secret

    # Valid secret matches
    assert verify_webhook_secret(secret, secret_hash) is True

    # Tampered secret fails
    assert verify_webhook_secret("tampered_secret", secret_hash) is False
    assert verify_webhook_secret("", secret_hash) is False


@pytest.mark.asyncio
async def test_rate_limit_retry_handling():
    token = "mock_token_for_retry_test"
    # Should succeed through mock
    res = await TelegramApiService.send_message_with_retry(
        raw_token=token,
        chat_id=12345678,
        text="Hello from test with retry",
    )
    assert res.get("ok") is True
