import uuid
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from modules.billing.wallet_service import WalletService
from modules.tenants.models import Tenant
from core.exceptions import InsufficientFundsError, ValidationError


@pytest.mark.asyncio
async def test_wallet_credit_debit_and_immutable_checksum(db_session: AsyncSession):
    tenant_id = uuid.uuid4()
    # Create tenant first to satisfy foreign key constraint
    tenant = Tenant(
        id=tenant_id,
        name=f"Wallet Org {tenant_id.hex[:6]}",
        slug=f"wallet-org-{tenant_id.hex[:6]}",
        plan_id="free",
    )
    db_session.add(tenant)
    await db_session.commit()

    wallet_service = WalletService(db_session)

    # 1. Initial wallet creation
    wallet = await wallet_service.get_or_create_wallet(tenant_id)
    assert wallet.balance == 0
    assert wallet.currency == "INR"

    # 2. Credit wallet
    tx_credit = await wallet_service.credit(
        tenant_id=tenant_id,
        amount=50000,  # ₹500
        reference_type="topup",
        description="Initial deposit",
        reference_id="dep_001",
    )
    assert tx_credit.amount == 50000
    assert tx_credit.balance_after == 50000
    assert tx_credit.transaction_type == "credit"
    assert len(tx_credit.checksum) == 64  # Valid SHA-256

    # Verify wallet balance
    assert wallet.balance == 50000

    # 3. Debit wallet
    tx_debit = await wallet_service.debit(
        tenant_id=tenant_id,
        amount=20000,  # ₹200
        reference_type="subscription",
        description="Monthly plan charge",
        reference_id="sub_001",
    )
    assert tx_debit.amount == 20000
    assert tx_debit.balance_after == 30000
    assert tx_debit.transaction_type == "debit"
    assert wallet.balance == 30000

    # 4. Overdraft attempt must raise InsufficientFundsError
    with pytest.raises(InsufficientFundsError):
        await wallet_service.debit(
            tenant_id=tenant_id,
            amount=999999,
            reference_type="subscription",
            description="Failed debit",
        )

    # 5. Invalid amount
    with pytest.raises(ValidationError):
        await wallet_service.credit(tenant_id, 0, "test", "test")

    # 6. Verify ledger history
    history = await wallet_service.get_transactions(tenant_id)
    assert len(history) == 2
    assert history[0].id == tx_debit.id  # Newest first
    assert history[1].id == tx_credit.id
