import uuid from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.ext.asyncio import AsyncSession from app.core.deps import get_current_user, get_db_session, require_study_member from app.crud import comment as comment_crud from app.crud import audit as audit_crud from app.crud import study as study_crud from app.schemas.comment import CommentCreate, CommentRead router = APIRouter() async def _ensure_study_exists(db: AsyncSession, study_id: uuid.UUID): study = await study_crud.get(db, study_id) if not study: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Study not found") return study @router.post( "/", response_model=CommentRead, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_study_member())], ) async def create_comment( study_id: uuid.UUID, entity_type: str, entity_id: uuid.UUID, comment_in: CommentCreate, db: AsyncSession = Depends(get_db_session), current_user=Depends(get_current_user), ) -> CommentRead: await _ensure_study_exists(db, study_id) comment = await comment_crud.create_comment( db, study_id=study_id, entity_type=entity_type, entity_id=entity_id, comment_in=comment_in, created_by=current_user.id, ) await audit_crud.log_action( db, study_id=study_id, entity_type=entity_type, entity_id=entity_id, action="CREATE_COMMENT", detail=f"Comment created by {current_user.username}", operator_id=current_user.id, operator_role=current_user.role, ) return comment @router.get( "/", response_model=list[CommentRead], dependencies=[Depends(require_study_member())], ) async def list_comments( study_id: uuid.UUID, entity_type: str, entity_id: uuid.UUID, db: AsyncSession = Depends(get_db_session), ) -> list[CommentRead]: await _ensure_study_exists(db, study_id) comments = await comment_crud.list_comments(db, study_id, entity_type, entity_id) return list(comments)