# backend/app/api/v1/endpoints/billing.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, text
from app.api.deps import get_db, get_current_user
from app.models.identity import User, Wallet
from app.models.audit import FinancialLedger # JAVÍTVA: Tranzakciós napló
import secrets

router = APIRouter()

@router.get("/balance")
async def get_balance(db: AsyncSession = Depends(get_db), current_user: User = Depends(get_current_user)):
    stmt = select(Wallet).where(Wallet.user_id == current_user.id)
    wallet = (await db.execute(stmt)).scalar_one_or_none()
    return {
        "earned": float(wallet.earned_credits) if wallet else 0,
        "purchased": float(wallet.purchased_credits) if wallet else 0,
        "service_coins": float(wallet.service_coins) if wallet else 0
    }

@router.post("/vouchers/redeem")
async def redeem_voucher(code: str, db: AsyncSession = Depends(get_db), current_user: User = Depends(get_current_user)):
    check = await db.execute(text("SELECT * FROM data.vouchers WHERE code = :c AND is_used = False"), {"c": code.upper()})
    voucher = check.fetchone()
    if not voucher:
        raise HTTPException(status_code=400, detail="Érvénytelen kód.")

    stmt = select(Wallet).where(Wallet.user_id == current_user.id)
    wallet = (await db.execute(stmt)).scalar_one_or_none()
    wallet.purchased_credits += voucher.value

    db.add(FinancialLedger(user_id=current_user.id, amount=voucher.value, transaction_type="VOUCHER_REDEEM", details={"code": code}))
    await db.execute(text("UPDATE data.vouchers SET is_used=True, used_by=:u WHERE id=:v"), {"u": current_user.id, "v": voucher.id})
    await db.commit()
    return {"status": "success", "added": float(voucher.value)}