# /opt/docker/dev/service_finder/backend/app/api/v1/endpoints/assets.py
import uuid
import logging
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 import Asset, AssetCost
from app.models.identity import User
from app.services.cost_service import cost_service
from app.services.asset_service import AssetService
from app.schemas.asset_cost import AssetCostCreate, AssetCostResponse
from app.schemas.asset import AssetResponse, AssetCreate

router = APIRouter()

@router.get("/vehicles", response_model=List[AssetResponse])
async def get_user_vehicles(
    skip: int = 0,
    limit: int = 100,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Get all vehicles/assets belonging to the current user or their organization.
    
    This endpoint returns a paginated list of vehicles that the authenticated user
    has access to (either as owner or through organization membership).
    """
    # Query assets where user is owner or organization member
    from sqlalchemy import or_
    
    # First, get user's organization memberships
    from app.models.marketplace.organization import OrganizationMember
    org_stmt = select(OrganizationMember.organization_id).where(
        OrganizationMember.user_id == current_user.id
    )
    org_result = await db.execute(org_stmt)
    user_org_ids = [row[0] for row in org_result.all()]
    
    # Build query: assets owned by user OR assets in user's organizations
    stmt = (
        select(Asset)
        .where(
            or_(
                Asset.owner_person_id == current_user.id,
                Asset.owner_org_id.in_(user_org_ids) if user_org_ids else False,
                Asset.operator_person_id == current_user.id,
                Asset.operator_org_id.in_(user_org_ids) if user_org_ids else False
            )
        )
        .order_by(Asset.created_at.desc())
        .offset(skip)
        .limit(limit)
        .options(selectinload(Asset.catalog))
    )
    
    result = await db.execute(stmt)
    assets = result.scalars().all()
    
    return assets

@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()


@router.post("/vehicles", response_model=AssetResponse, status_code=status.HTTP_201_CREATED)
async def create_or_claim_vehicle(
    payload: AssetCreate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Új jármű hozzáadása vagy meglévő jármű igénylése a flottához.
    
    A végpont a következőket végzi:
    - Ellenőrzi a felhasználó járműlimitjét
    - Ha a VIN már létezik, tulajdonjog-átvitelt kezdeményez
    - Ha új, létrehozza a járművet és a kapcsolódó digitális ikreket
    - XP jutalom adása a felhasználónak
    """
    try:
        asset = await AssetService.create_or_claim_vehicle(
            db=db,
            user_id=current_user.id,
            org_id=payload.organization_id,
            vin=payload.vin,
            license_plate=payload.license_plate,
            catalog_id=payload.catalog_id
        )
        return asset
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        logger = logging.getLogger(__name__)
        logger.error(f"Vehicle creation error: {e}")
        raise HTTPException(status_code=500, detail="Belső szerverhiba a jármű létrehozásakor")