from backend.core.config import get_app_settings
from backend.core.security.security import hash_password
from backend.db.models import Users
from backend.schemas import UserCreate, UserProfile
from sqlalchemy.orm import Session
from uuid import UUID

from backend.schemas.user.user import UserSeeds

settings = get_app_settings()

class RepositoryUsers:
  def __init__(self):
    self.user = Users()

  def get_all(self, skip: int = 0, limit: int = 100):
    return self.user.query.offset(skip).limit(limit).all()

  def get_by_username(self, username: str):
    return self.user.query.filter_by(username=username).first()

  def get_by_id(self, user_id: str):
    return self.user.query.filter_by(id=UUID(str(user_id))).one()

  def create(self, db: Session, user: UserCreate | UserSeeds):
    try:
      password = getattr(user, "password")
      db_user = Users(**user.dict(exclude={"password"}), password=hash_password(password))
      db.add(db_user)
      db.commit()
    except Exception:
      db.rollback()
      raise

    db.refresh(db_user)
    return db_user

  def update(self, db: Session, user: UserProfile, user_id: str):
    db_user = self.get_by_id(user_id)
    if not db_user:
      return None
    try:
      user.update_password()
      self.user.query.where(Users.id == user_id).update(user.dict(exclude_unset=True, exclude_none=True))
      db.commit()
    except Exception:
      db.rollback()
      raise

    db.refresh(db_user)
    return db_user
