from sqlalchemy.ext.asyncio import AsyncSession
from decimal import Decimal
from app.models import Wallet, TransactionType
from app.crud.wallet import get_user_wallet, create_transaction
from app.utils.exceptions import InsufficientFundsError


async def deposit_funds(db: AsyncSession, user_id: int, amount: Decimal) -> Wallet:
    wallet = await get_user_wallet(db, user_id)
    if not wallet:
        raise ValueError("Wallet not found")

    wallet.balance += amount

    await create_transaction(
        db=db,
        user_id=user_id,
        wallet_id=wallet.id,
        transaction_type=TransactionType.DEPOSIT,
        amount=amount,
        balance_after=wallet.balance,
        description=f"Deposit of ${amount}",
    )

    await db.commit()
    await db.refresh(wallet)
    return wallet


async def withdraw_funds(db: AsyncSession, user_id: int, amount: Decimal) -> Wallet:
    wallet = await get_user_wallet(db, user_id)
    if not wallet:
        raise ValueError("Wallet not found")

    if wallet.balance < amount:
        raise InsufficientFundsError()

    wallet.balance -= amount

    await create_transaction(
        db=db,
        user_id=user_id,
        wallet_id=wallet.id,
        transaction_type=TransactionType.WITHDRAWAL,
        amount=-amount,
        balance_after=wallet.balance,
        description=f"Withdrawal of ${amount}",
    )

    await db.commit()
    await db.refresh(wallet)
    return wallet
