from sqlalchemy.orm import Session
from backend.core.security.hasher import get_hasher
from backend.core.security import create_access_token
from backend.core.security.security import create_refresh_token
from backend.repos import RepositoryUsers
from backend.schemas import UserRequest, UserCreate
from backend.services._base_service import BaseService

class UserService(BaseService):
  def __init__(self):
    self.repos = RepositoryUsers()

  def generate_token(self, user_id: str):
    access_token = create_access_token(data={"sub": str(user_id)})
    refresh_token = create_refresh_token(data={"sub": str(user_id)})
    return access_token, refresh_token

  def get_by_username(self, username: str):
    return self.repos.get_by_username(username)

  def get_access_token(self, user_id: str):
    return create_access_token(data={"sub": str(user_id)})

  def get_all(self, skip: int = 0, limit: int = 100):
    return self.repos.get_all(skip=skip, limit=limit)

  def get_by_id(self, user_id: str):
    return self.repos.get_by_id(user_id)

  def create(self, db: Session, user: UserCreate):
    return self.repos.create(db=db, user=user)

  def check_exist(self, user: UserRequest):
    db_user = self.get_by_username(username=user.username)
    if not db_user:
      return False
    if not get_hasher().verify(password=user.password, hashed=db_user.password):
      return False
    return db_user

  def update(self, db: Session, user: UserCreate, user_id: str):
    return self.repos.update(db=db, user=user, user_id=user_id)
