import secrets
from sqlalchemy.orm import Session as DBSession
from app.models.session import Session as SessionModel

def create_session(db: DBSession, user_id: int) -> str:
    token = secrets.token_hex(32)
    session = SessionModel(user_id=user_id, token=token)
    db.add(session)
    db.commit()
    db.refresh(session)
    return token

def get_user_by_token(db: DBSession, token: str):
    session = db.query(SessionModel).filter_by(token=token).first()
    return session.user if session else None

def delete_session(db: DBSession, token: str):
    db.query(SessionModel).filter_by(token=token).delete()
    db.commit()
