from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session
from datetime import datetime

from database import get_session
from models.session import Session as SessionModel, SessionCreate
from repositories.session_repository import SessionRepository

router = APIRouter(prefix="/sessions", tags=["Sessions"])


def get_repo(db: Session = Depends(get_session)):
    return SessionRepository(db)


# START SESSION
@router.post("/start", response_model=SessionModel)
def start_session(repo: SessionRepository = Depends(get_repo)):
    session = SessionModel(start_time=datetime.utcnow())
    return repo.create(session)


# GET ALL
@router.get("/", response_model=list[SessionModel])
def get_all(repo: SessionRepository = Depends(get_repo)):
    return repo.get_all()


# GET ONE
@router.get("/{session_id}", response_model=SessionModel)
def get_one(session_id: int, repo: SessionRepository = Depends(get_repo)):
    session = repo.get_one(session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Session not found")
    return session


# END SESSION
@router.put("/{session_id}/end", response_model=SessionModel)
def end_session(session_id: int, repo: SessionRepository = Depends(get_repo)):
    session = repo.end_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Session not found")
    return session

# UPDATE SESSION (optional, can be used for other updates if needed)
@router.put("/{session_id}", response_model=SessionModel)
def update_session(session_id: int, updated_session: SessionCreate, repo: SessionRepository = Depends(get_repo)):
    session_obj = SessionModel(**updated_session.model_dump())
    updated = repo.update(session_id, session_obj)
    if not updated:
        raise HTTPException(status_code=404, detail="Session not found")
    return updated