from sqlalchemy.orm import Session, joinedload
from app.infrastructure.database.models.users import User


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

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

    def get_all_with_role(self):
        return self.db.query(User) \
            .options(joinedload(User.role)) \
            .all()

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

    def get_by_login(self, user_login: str):
        return self.db.query(User).filter(User.login == user_login) \
            .options(joinedload(User.role)) \
            .first()

    def create(self, user: User):
        self.db.add(user)
        self.db.commit()
        self.db.refresh(user)
        return user

    def update(self, user: User):
        self.db.commit()
        return user

    def delete(self, user_id: int):
        user = self.db.query(User).filter(User.id == user_id).first()
        if user:
            self.db.delete(user)
            self.db.commit()
            return user
        return None
