from typing import List, Optional
from sqlalchemy.orm import Session
from app.core.entities.truck import TruckEntity
from app.infrastructure.database.models.trucks import Truck
from app.infrastructure.database.repository.truck_repository import TrucksRepository


class TrucksService:
    def __init__(self, db: Session):
        self.repository = TrucksRepository(db)

    def get_all_trucks(self) -> List[TruckEntity]:
        trucks = self.repository.get_all()
        return [
            TruckEntity(
                id=truck.id,
                name=truck.name,
                capacity=truck.capacity,
                volume=truck.volume,
                delivery_orders=[do.id for do in truck.delivery_orders] if truck.delivery_orders else []
            )
            for truck in trucks
        ]

    def get_truck_by_id(self, truck_id: int) -> Optional[TruckEntity]:
        truck = self.repository.get_by_id(truck_id)
        if truck:
            return TruckEntity(
                id=truck.id,
                name=truck.name,
                capacity=truck.capacity,
                volume=truck.volume,
                delivery_orders=[do.id for do in truck.delivery_orders] if truck.delivery_orders else []
            )
        return None

    def create_truck(self, entity: TruckEntity) -> TruckEntity:
        truck_model = Truck(
            name=entity.name,
            capacity=entity.capacity,
            volume=entity.volume
        )
        created_truck = self.repository.create(truck_model)
        return TruckEntity(
            id=created_truck.id,
            name=created_truck.name,
            capacity=created_truck.capacity,
            volume=created_truck.volume,
            delivery_orders=[]
        )

    def update_truck(self, truck_id: int, entity: TruckEntity) -> Optional[TruckEntity]:
        truck_model = self.repository.get_by_id(truck_id)
        if truck_model:
            truck_model.name = entity.name
            truck_model.capacity = entity.capacity
            truck_model.volume = entity.volume
            self.repository.update(truck_model)
            return TruckEntity(
                id=truck_model.id,
                name=truck_model.name,
                capacity=truck_model.capacity,
                volume=truck_model.volume,
                delivery_orders=[do.id for do in truck_model.delivery_orders] if truck_model.delivery_orders else []
            )
        return None

    def delete_truck(self, truck_id: int) -> bool:
        return self.repository.delete(truck_id) is not None
