# /opt/docker/dev/service_finder/backend/app/api/v1/endpoints/assets.py
import uuid
from typing import Any, Dict, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, desc
from sqlalchemy.orm import selectinload

from app.db.session import get_db
from app.api.deps import get_current_user
from app.models.asset import Asset, AssetCost
from app.models.identity import User
from app.services.cost_service import cost_service
from app.schemas.asset_cost import AssetCostCreate, AssetCostResponse
from app.schemas.asset import AssetResponse

router = APIRouter()

@router.get("/{asset_id}/financial-summary", response_model=Dict[str, Any])
async def get_asset_financial_report(
    asset_id: uuid.UUID,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    MB 2.0 Dinamikus Pénzügyi Riport.
    Visszaadja a kategóriákra bontott és az összesített költségeket (Local/EUR).
    """
    # 1. Jogosultság ellenőrzése (Csak a tulajdonos vagy admin láthatja)
    # (Itt egy gyors check, hogy az asset az övé-e)
    
    try:
        return await cost_service.get_asset_financial_summary(db, asset_id)
    except Exception as e:
        raise HTTPException(status_code=500, detail="Hiba a riport generálásakor")

@router.get("/{asset_id}/costs", response_model=List[AssetCostResponse])
async def list_asset_costs(
    asset_id: uuid.UUID,
    skip: int = 0,
    limit: int = 100,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Tételes költséglista lapozással (Pagination)."""
    stmt = (
        select(AssetCost)
        .where(AssetCost.asset_id == asset_id)
        .order_by(desc(AssetCost.date))
        .offset(skip)
        .limit(limit)
    )
    res = await db.execute(stmt)
    return res.scalars().all()