from sqlalchemy import asc
from sqlalchemy.orm import Session, joinedload
from app.infrastructure.database.models.delivery_orders import DeliveryOrder


class DeliveryOrdersRepository:
    def __init__(self, db: Session):
        self.db = db

    def get_all(self):
        return self.db.query(DeliveryOrder).all()

    def get_all_with_trucks(self):
        return self.db.query(DeliveryOrder) \
            .options(joinedload(DeliveryOrder.truck)) \
            .all()

    def get_all_by_total_order_id(self, total_order_id):
        return self.db.query(DeliveryOrder).filter(DeliveryOrder.total_order_id == total_order_id) \
            .options(joinedload(DeliveryOrder.truck)) \
            .order_by(asc(DeliveryOrder.deadline)) \
            .all()

    def get_by_id(self, delivery_order_id: int):
        return self.db.query(DeliveryOrder).filter(DeliveryOrder.id == delivery_order_id) \
            .options(joinedload(DeliveryOrder.truck)) \
            .first()

    def create(self, delivery_order: DeliveryOrder):
        self.db.add(delivery_order)
        self.db.commit()
        self.db.refresh(delivery_order)
        return delivery_order

    def update(self, delivery_order: DeliveryOrder):
        self.db.commit()
        return delivery_order

    def delete(self, delivery_order_id: int):
        delivery_order = self.db.query(DeliveryOrder).filter(DeliveryOrder.id == delivery_order_id).first()
        if delivery_order:
            self.db.delete(delivery_order)
            self.db.commit()
            return delivery_order
        return None
