from typing import Any, List from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.core.deps import get_current_active_user, get_db from app.models.user import User from app.models.wallet import Wallet from app.models.cryptocurrency import Cryptocurrency from app.schemas.wallet import Wallet as WalletSchema router = APIRouter() @router.get("/", response_model=List[WalletSchema]) def read_wallets( db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user), ) -> Any: wallets = db.query(Wallet).filter(Wallet.user_id == current_user.id).all() return wallets @router.get("/{cryptocurrency_id}", response_model=WalletSchema) def read_wallet( cryptocurrency_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user), ) -> Any: wallet = db.query(Wallet).filter( Wallet.user_id == current_user.id, Wallet.cryptocurrency_id == cryptocurrency_id ).first() if not wallet: # Create wallet if it doesn't exist crypto = db.query(Cryptocurrency).filter(Cryptocurrency.id == cryptocurrency_id).first() if not crypto: raise HTTPException(status_code=404, detail="Cryptocurrency not found") wallet = Wallet( user_id=current_user.id, cryptocurrency_id=cryptocurrency_id, available_balance=0.0, locked_balance=0.0 ) db.add(wallet) db.commit() db.refresh(wallet) return wallet @router.post("/{cryptocurrency_id}/lock") def lock_funds( cryptocurrency_id: int, amount: float, db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user), ) -> Any: wallet = db.query(Wallet).filter( Wallet.user_id == current_user.id, Wallet.cryptocurrency_id == cryptocurrency_id ).first() if not wallet: raise HTTPException(status_code=404, detail="Wallet not found") if wallet.available_balance < amount: raise HTTPException(status_code=400, detail="Insufficient funds") wallet.available_balance -= amount wallet.locked_balance += amount db.add(wallet) db.commit() db.refresh(wallet) return {"message": "Funds locked successfully", "locked_amount": amount} @router.post("/{cryptocurrency_id}/unlock") def unlock_funds( cryptocurrency_id: int, amount: float, db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user), ) -> Any: wallet = db.query(Wallet).filter( Wallet.user_id == current_user.id, Wallet.cryptocurrency_id == cryptocurrency_id ).first() if not wallet: raise HTTPException(status_code=404, detail="Wallet not found") if wallet.locked_balance < amount: raise HTTPException(status_code=400, detail="Insufficient locked funds") wallet.locked_balance -= amount wallet.available_balance += amount db.add(wallet) db.commit() db.refresh(wallet) return {"message": "Funds unlocked successfully", "unlocked_amount": amount}