from sqlalchemy.ext.asyncio import AsyncSession
from database.models import User, Transaction
from database.crud import get_user_by_telegram_id

async def charge_wallet(session: AsyncSession, telegram_id: int, amount: float, charge_type: str = 'rial_charge') -> bool:
    """شارژ کیف پول کاربر"""
    user = await get_user_by_telegram_id(session, telegram_id)
    if not user:
        return False
        
    user.wallet_balance += amount
    
    # ثبت تراکنش
    new_tx = Transaction(
        user_id=user.id,
        amount=amount,
        type=charge_type,
        status='completed'
    )
    session.add(new_tx)
    await session.commit()
    return True

async def deduct_wallet(session: AsyncSession, telegram_id: int, amount: float, description: str = 'purchase') -> bool:
    """کسر از کیف پول کاربر (هنگام خرید)"""
    user = await get_user_by_telegram_id(session, telegram_id)
    if not user or user.wallet_balance < amount:
        return False
        
    user.wallet_balance -= amount
    
    # ثبت تراکنش با مبلغ منفی
    new_tx = Transaction(
        user_id=user.id,
        amount=-amount,
        type=description,
        status='completed'
    )
    session.add(new_tx)
    await session.commit()
    return True
