from fastapi import APIRouter, Depends
from sqlalchemy import select
from app.core.database import get_db
from app.core.dependencies import require_permission
from app.models.wallet import Wallet
from app.models.wallet_history import WalletHistory
router=APIRouter(prefix="/wallets",tags=["Wallets"])

@router.get("/{customer_id}")
async def wallet(customer_id:int,user=Depends(require_permission("customers.view")),db=Depends(get_db)):
    w=await db.scalar(select(Wallet).where(Wallet.customer_id==customer_id,Wallet.brand_id==user.brand_id))
    if not w: return {"success":False,"message":"Wallet not found","data":None}
    return {"success":True,"message":"Wallet","data":{"customer_id":customer_id,"balance":w.balance}}

@router.get("/{customer_id}/history")
async def history(customer_id:int,user=Depends(require_permission("customers.view")),db=Depends(get_db)):
    rows=(await db.scalars(select(WalletHistory).where(WalletHistory.customer_id==customer_id,WalletHistory.brand_id==user.brand_id).order_by(WalletHistory.id.desc()).limit(100))).all()
    return {"success":True,"message":"Wallet history","data":[{"id":x.id,"entry_type":x.entry_type,"points":x.points,"balance_after":x.balance_after,"description":x.description} for x in rows]}
