from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List

from app.db.session import get_db
from app.schemas.fleet import VehicleCreate, VehicleResponse, EventCreate, EventResponse, TCOStats
from app.models.vehicle import Vehicle
from app.services.fleet_service import add_vehicle_event, calculate_tco

# Mock user dependency (később cserélendő a JWT-re)
async def get_mock_current_user():
    return 2 # Good Guy

router = APIRouter()

# --- VEHICLE ENDPOINTS ---

@router.post("/vehicles", response_model=VehicleResponse, status_code=status.HTTP_201_CREATED)
async def create_vehicle(
    vehicle_in: VehicleCreate,
    db: AsyncSession = Depends(get_db),
    user_id: int = Depends(get_mock_current_user)
):
    new_vehicle = Vehicle(**vehicle_in.model_dump(), user_id=user_id, current_odometer=vehicle_in.initial_odometer)
    db.add(new_vehicle)
    await db.commit()
    await db.refresh(new_vehicle)
    return new_vehicle

@router.get("/vehicles", response_model=List[VehicleResponse])
async def get_my_vehicles(
    db: AsyncSession = Depends(get_db),
    user_id: int = Depends(get_mock_current_user)
):
    from sqlalchemy import select
    result = await db.execute(select(Vehicle).where(Vehicle.user_id == user_id))
    return result.scalars().all()

# --- EVENT / SERVICE BOOK ENDPOINTS ---

@router.post("/vehicles/{vehicle_id}/events", response_model=EventResponse)
async def add_event(
    vehicle_id: int,
    event_in: EventCreate,
    db: AsyncSession = Depends(get_db),
    user_id: int = Depends(get_mock_current_user)
):
    """
    Új esemény (szerviz, tankolás) rögzítése.
    Automatikusan kezeli a szolgáltatókat és a km óra állást.
    """
    result = await add_vehicle_event(db, vehicle_id, event_in, user_id)
    
    if isinstance(result, dict) and "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
        
    return result

@router.get("/vehicles/{vehicle_id}/stats", response_model=TCOStats)
async def get_vehicle_stats(vehicle_id: int, db: AsyncSession = Depends(get_db)):
    """Költségek elemzése és TCO mutatók"""
    return await calculate_tco(db, vehicle_id)