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

from app.core.deps import get_db, get_current_user
from app.integrations.motornet import MotornetUnavailableError
from app.services import vehicle_lookup as svc
from app.schemas.vehicle import VehicleLookupResponse, VersionSelectRequest

router = APIRouter()


@router.get("/lookup", response_model=VehicleLookupResponse)
async def lookup_vehicle(
    plate: str = Query(..., min_length=5, max_length=10),
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
):
    try:
        return await svc.lookup(plate, db)
    except MotornetUnavailableError:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Lookup targa non disponibile. Inserire i dati del veicolo manualmente.",
        )


@router.post("/{plate}/select-version", status_code=status.HTTP_204_NO_CONTENT)
async def select_version(
    plate: str,
    body: VersionSelectRequest,
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
):
    await svc.select_version(plate, body.motornet_code, db)
