from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.db.session import get_session from app.models.car import Car from app.schemas.car import CarCreate, CarRead, CarUpdate router = APIRouter(prefix="/cars", tags=["cars"]) @router.post("", response_model=CarRead, status_code=status.HTTP_201_CREATED) async def create_car(payload: CarCreate, session: AsyncSession = Depends(get_session)) -> Car: car = Car(**payload.model_dump()) session.add(car) await session.commit() await session.refresh(car) return car @router.get("", response_model=list[CarRead]) async def list_cars(owner_id: int, session: AsyncSession = Depends(get_session)) -> list[Car]: result = await session.execute( select(Car).where(Car.owner_id == owner_id).order_by(Car.created_at.desc()) ) return list(result.scalars()) @router.get("/{car_id}", response_model=CarRead) async def get_car(car_id: int, session: AsyncSession = Depends(get_session)) -> Car: car = await session.get(Car, car_id) if car is None: raise HTTPException(status_code=404, detail="Car not found") return car @router.patch("/{car_id}", response_model=CarRead) async def update_car( car_id: int, payload: CarUpdate, session: AsyncSession = Depends(get_session) ) -> Car: car = await session.get(Car, car_id) if car is None: raise HTTPException(status_code=404, detail="Car not found") for field, value in payload.model_dump(exclude_unset=True).items(): setattr(car, field, value) await session.commit() await session.refresh(car) return car @router.delete("/{car_id}", status_code=status.HTTP_204_NO_CONTENT) async def delete_car(car_id: int, session: AsyncSession = Depends(get_session)) -> None: car = await session.get(Car, car_id) if car is None: raise HTTPException(status_code=404, detail="Car not found") await session.delete(car) await session.commit()