from typing import List

from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session

from app.core.usecases.auth_service import verify_token
from app.infrastructure.database.dependencies import get_db
from app.core.entities.truck import TruckEntity
from app.core.usecases.truck_service import TrucksService
from app.infrastructure.database.models.users import User

router = APIRouter()


@router.get("/trucks", response_model=List[TruckEntity])
def read_trucks(db: Session = Depends(get_db),
                current_user: User = Depends(verify_token)):
    service = TrucksService(db)
    return service.get_all_trucks()


@router.get("/trucks/{truck_id}", response_model=TruckEntity)
def read_truck(truck_id: int, db: Session = Depends(get_db),
               current_user: User = Depends(verify_token)):
    service = TrucksService(db)
    truck = service.get_truck_by_id(truck_id)
    if truck is None:
        raise HTTPException(status_code=404, detail="Truck not found")
    return truck


@router.post("/trucks", response_model=TruckEntity)
def create_truck(truck: TruckEntity, db: Session = Depends(get_db),
                 current_user: User = Depends(verify_token)):
    service = TrucksService(db)
    return service.create_truck(truck)


@router.put("/trucks/{truck_id}", response_model=TruckEntity)
def update_truck(truck_id: int, truck: TruckEntity, db: Session = Depends(get_db),
                 current_user: User = Depends(verify_token)):
    service = TrucksService(db)
    updated_truck = service.update_truck(truck_id, truck)
    if updated_truck is None:
        raise HTTPException(status_code=404, detail="Truck not found")
    return updated_truck


@router.delete("/trucks/{truck_id}", response_model=bool)
def delete_truck(truck_id: int, db: Session = Depends(get_db),
                 current_user: User = Depends(verify_token)):
    service = TrucksService(db)
    success = service.delete_truck(truck_id)
    if not success:
        raise HTTPException(status_code=404, detail="Truck not found")
    return success
