from sqlalchemy.orm import Session, joinedload
from app.infrastructure.database.models.accessory import Accessory


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

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

    def get_with_cities_all(self):
        return self.db.query(Accessory) \
            .options(joinedload(Accessory.city)) \
            .all()

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

    def create(self, accessory: Accessory):
        self.db.add(accessory)
        self.db.commit()
        self.db.refresh(accessory)
        return accessory

    def update(self, accessory: Accessory):
        self.db.commit()
        return accessory

    def delete(self, accessory_id: int):
        accessory = self.db.query(Accessory).filter(Accessory.id == accessory_id).first()
        if accessory:
            self.db.delete(accessory)
            self.db.commit()
            return accessory
        return None
