from sqlalchemy.orm import Session
from modules.auth.models import User
from modules.auth.schemas import UserResponse
from modules.auth.security import hash_password
from core.exceptions import conflict_exception
import uuid


def create_user(username: str, password: str, name: str, db: Session) -> UserResponse:
    """
    Create a new user in the database.
    Hashes the password before storing it.
    Returns the created user object.
    """
    if db is None:
        raise ValueError("Database session is required")

    # Check if the user already exists
    existing_user = db.query(User).filter(User.username == username).first()
    if existing_user:
        raise conflict_exception("Username already exists")

    hashed_password = hash_password(password)
    user_uuid = str(uuid.uuid4())
    user = User(
        username=username, hashed_password=hashed_password, name=name, uuid=user_uuid
    )
    db.add(user)
    db.commit()
    db.refresh(user)  # Loads the generated ID
    return UserResponse.model_validate(user)  # Converts SQLAlchemy model -> Pydantic
