from sqlalchemy import asc
from sqlalchemy.orm import Session, joinedload

from app.infrastructure.database.models.accessory import Accessory
from app.infrastructure.database.models.delivery_accessories import DeliveryAccessory


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

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

    def get_all_by_order_id(self, delivery_order_id):
        return self.db.query(DeliveryAccessory) \
            .options(joinedload(DeliveryAccessory.accessory).joinedload(Accessory.city)) \
            .filter(DeliveryAccessory.delivery_order_id == delivery_order_id) \
            .order_by(asc(DeliveryAccessory.queue)) \
            .all()

    def get_by_id(self, delivery_accessory_id: int):
        return self.db.query(DeliveryAccessory).filter(DeliveryAccessory.id == delivery_accessory_id).first()

    def create(self, delivery_accessory: DeliveryAccessory):
        self.db.add(delivery_accessory)
        self.db.commit()
        self.db.refresh(delivery_accessory)
        return delivery_accessory

    def update(self, delivery_accessory: DeliveryAccessory):
        self.db.commit()
        return delivery_accessory

    def delete(self, delivery_accessory_id: int):
        delivery_accessory = self.db.query(DeliveryAccessory).filter(
            DeliveryAccessory.id == delivery_accessory_id).first()
        if delivery_accessory:
            self.db.delete(delivery_accessory)
            self.db.commit()
            return delivery_accessory
        return None
