from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import get_db
from app.services.asset_service import AssetService
from app.api import deps
from typing import List

router = APIRouter()

# Secured endpoint: Closed premium ecosystem
@router.get("/makes", response_model=List[str])
async def list_makes(
    db: AsyncSession = Depends(get_db),
    current_user = Depends(deps.get_current_user)
):
    """1. Szint: Márkák listázása."""
    return await AssetService.get_makes(db)

# Secured endpoint: Closed premium ecosystem
@router.get("/models", response_model=List[str])
async def list_models(
    make: str,
    vehicle_class: str = None,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(deps.get_current_user)
):
    """2. Szint: Típusok listázása egy adott márkához, opcionálisan vehicle_class szerint szűrve."""
    # Handle empty or invalid parameters gracefully
    if not make or make.strip() == "":
        return []
    
    models = await AssetService.get_models(db, make, vehicle_class)
    # Return empty list instead of 404 - frontend can handle empty dropdown
    return models or []

# Secured endpoint: Closed premium ecosystem
@router.get("/generations", response_model=List[str])
async def list_generations(
    make: str,
    model: str,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(deps.get_current_user)
):
    """3. Szint: Generációk/Évjáratok listázása."""
    # Handle empty or invalid parameters gracefully
    if not make or not model or make.strip() == "" or model.strip() == "":
        return []
    
    generations = await AssetService.get_generations(db, make, model)
    # Return empty list instead of 404 - frontend can handle empty dropdown
    return generations or []

# Secured endpoint: Closed premium ecosystem
@router.get("/engines")
async def list_engines(
    make: str,
    model: str,
    gen: str,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(deps.get_current_user)
):
    """4. Szint: Motorváltozatok és technikai specifikációk."""
    engines = await AssetService.get_engines(db, make, model, gen)
    if not engines:
        raise HTTPException(status_code=404, detail="Nincs motorváltozat adat.")
    
    # Itt visszaküldjük a teljes katalógus objektumokat (ID, motorváltozat, specifikációk)
    return [
        {
            "id": e.id,
            "variant": e.engine_variant,
            "engine_code": e.engine_code,
            "fuel_type": e.fuel_type,
            "factory_data": e.factory_data
        } for e in engines
    ]