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

from app.infrastructure.database.models.total_orders import TotalOrder


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

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

    def get_all_with_users_and_statuses(self):
        return self.db.query(TotalOrder) \
            .options(joinedload(TotalOrder.user)) \
            .options(joinedload(TotalOrder.status)) \
            .order_by(desc(TotalOrder.order_datetime)) \
            .all()

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

    def create(self, total_order: TotalOrder):
        self.db.add(total_order)
        self.db.commit()
        self.db.refresh(total_order)
        return total_order

    def update(self, total_order: TotalOrder):
        self.db.commit()
        return total_order

    def delete(self, total_order_id: int):
        total_order = self.db.query(TotalOrder).filter(TotalOrder.id == total_order_id).first()
        if total_order:
            self.db.delete(total_order)
            self.db.commit()
            return total_order
        return None
