"""Tests for wallet provider and mock wallet."""

import hashlib

import pytest

from discourse_toll.wallet import WalletProvider, MockWallet


@pytest.mark.asyncio
async def test_mock_create_invoice():
    mock = MockWallet()
    result = await mock.create_invoice(5, "test")
    assert "invoice" in result
    assert "payment_hash" in result
    assert len(result["payment_hash"]) == 64


@pytest.mark.asyncio
async def test_mock_lookup_unpaid():
    mock = MockWallet()
    result = await mock.create_invoice(5, "test")
    lookup = await mock.lookup_invoice(result["payment_hash"])
    assert not lookup["paid"]


@pytest.mark.asyncio
async def test_mock_pay_and_lookup():
    mock = MockWallet()
    result = await mock.create_invoice(5, "test")
    preimage = mock.mock_pay(result["payment_hash"])
    assert preimage is not None
    lookup = await mock.lookup_invoice(result["payment_hash"])
    assert lookup["paid"]
    assert lookup["preimage"] == preimage


@pytest.mark.asyncio
async def test_mock_preimage_valid():
    mock = MockWallet()
    result = await mock.create_invoice(5, "test")
    preimage = mock.get_preimage(result["payment_hash"])
    computed = hashlib.sha256(bytes.fromhex(preimage)).hexdigest()
    assert computed == result["payment_hash"]


@pytest.mark.asyncio
async def test_wallet_provider_stats():
    mock = MockWallet()
    provider = WalletProvider(mock)
    await provider.create_invoice(10, "test")
    stats = provider.stats()
    assert stats["total"] == 1
    assert stats["paid"] == 0
    assert stats["pending"] == 1


def test_verify_preimage():
    import os
    preimage = os.urandom(32).hex()
    payment_hash = hashlib.sha256(bytes.fromhex(preimage)).hexdigest()
    assert WalletProvider.verify_preimage(preimage, payment_hash)
    assert not WalletProvider.verify_preimage("aa" * 32, payment_hash)
