from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models import User, Wallet
from app.schemas.user import UserCreate
from app.utils.security import get_password_hash
from decimal import Decimal


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


async def get_user_by_email(db: AsyncSession, email: str) -> User | None:
    result = await db.execute(select(User).where(User.email == email))
    return result.scalar_one_or_none()


async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
    result = await db.execute(select(User).where(User.username == username))
    return result.scalar_one_or_none()


async def create_user(db: AsyncSession, user_data: UserCreate) -> User:
    user = User(
        email=user_data.email,
        username=user_data.username,
        password_hash=get_password_hash(user_data.password),
        display_name=user_data.display_name or user_data.username,
    )
    db.add(user)
    await db.flush()

    # Create wallet for user
    wallet = Wallet(
        user_id=user.id,
        balance=Decimal("0.00"),
        escrow=Decimal("0.00"),
    )
    db.add(wallet)
    await db.flush()
    await db.refresh(user)

    return user


async def update_user_stats(db: AsyncSession, user_id: int, won: bool) -> None:
    user = await get_user_by_id(db, user_id)
    if user:
        user.total_bets += 1
        if won:
            user.wins += 1
        else:
            user.losses += 1
        user.win_rate = user.wins / user.total_bets if user.total_bets > 0 else 0.0
        await db.flush()
