from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from decimal import Decimal
from app.models import Wallet, Transaction, TransactionType, TransactionStatus


async def get_user_wallet(db: AsyncSession, user_id: int) -> Wallet | None:
    result = await db.execute(
        select(Wallet).where(Wallet.user_id == user_id)
    )
    return result.scalar_one_or_none()


async def get_wallet_transactions(
    db: AsyncSession,
    user_id: int,
    limit: int = 50,
    offset: int = 0
) -> list[Transaction]:
    result = await db.execute(
        select(Transaction)
        .where(Transaction.user_id == user_id)
        .order_by(Transaction.created_at.desc())
        .limit(limit)
        .offset(offset)
    )
    return list(result.scalars().all())


async def create_transaction(
    db: AsyncSession,
    user_id: int,
    wallet_id: int,
    transaction_type: TransactionType,
    amount: Decimal,
    balance_after: Decimal,
    description: str,
    reference_id: int | None = None,
    status: TransactionStatus = TransactionStatus.COMPLETED,
) -> Transaction:
    transaction = Transaction(
        user_id=user_id,
        wallet_id=wallet_id,
        type=transaction_type,
        amount=amount,
        balance_after=balance_after,
        reference_id=reference_id,
        description=description,
        status=status,
    )
    db.add(transaction)
    await db.flush()
    return transaction
