from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import text
from app.api.deps import get_db, get_current_user

router = APIRouter() # EZ HIÁNYZOTT!

@router.get("/summary/{vehicle_id}")
async def get_vehicle_summary(vehicle_id: str, db: AsyncSession = Depends(get_db), current_user = Depends(get_current_user)):
    """
    Összesített jelentés egy járműhöz: kategóriánkénti költségek.
    """
    query = text("""
        SELECT 
            category, 
            SUM(amount) as total_amount,
            COUNT(*) as transaction_count
        FROM data.vehicle_expenses
        WHERE vehicle_id = :v_id
        GROUP BY category
    """)
    
    result = await db.execute(query, {"v_id": vehicle_id})
    rows = result.fetchall()
    
    total_cost = sum(row.total_amount for row in rows) if rows else 0
    
    return {
        "vehicle_id": vehicle_id,
        "total_cost": float(total_cost),
        "breakdown": [dict(row._mapping) for row in rows]
    }

@router.get("/trends/{vehicle_id}")
async def get_monthly_trends(vehicle_id: str, db: AsyncSession = Depends(get_db), current_user = Depends(get_current_user)):
    """
    Visszaadja az utolsó 6 hónap költéseit havi bontásban.
    """
    query = text("""
        SELECT 
            TO_CHAR(date, 'YYYY-MM') as month,
            SUM(amount) as monthly_total
        FROM data.vehicle_expenses
        WHERE vehicle_id = :v_id
        GROUP BY month
        ORDER BY month DESC
        LIMIT 6
    """)
    result = await db.execute(query, {"v_id": vehicle_id})
    return [dict(row._mapping) for row in result.fetchall()]