"""
This module provides users repository.
"""

# pylint: disable=E1136,E1131
# pylint: disable=unsupported-binary-operation
# pylint: disable=R0914

import itertools
from typing import TypeVar, Type, Optional
from sqlalchemy import and_
from sqlalchemy.orm import Session, joinedload
from app.models import User

T = TypeVar("T")


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

    def create_user(self, user_data: dict) -> User:
        db_user = User(**user_data)
        self.db.add(db_user)
        self.db.commit()
        self.db.refresh(db_user)

        return db_user

    def get_user(self, user_id: int) -> User:
        return (
            self.db.query(User)
            .options(joinedload(User.invited_users))
            .filter(User.id == user_id)
            .first()
        )

    def get_all_users(self) -> list[User]:
        return self.db.query(User).all()

    def update_user(self, user_id: int, user_data: dict) -> User:
        db_user = self.get_user(user_id)
        if db_user:
            for key, value in user_data.items():
                setattr(db_user, key, value)
            self.db.commit()
            self.db.refresh(db_user)
        return db_user

    def update_user_status(self, user_id: int, is_active: bool) -> User:
        db_user = self.get_user(user_id)
        if db_user:
            db_user.is_active = is_active
            self.db.commit()
            self.db.refresh(db_user)
        return db_user

    def delete_user(self, user_id: int) -> bool | User:
        db_user = self.get_user(user_id)
        if db_user:
            self.db.merge(db_user)
            self.db.delete(db_user)
            self.db.commit()
            return db_user
        return False
