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_roles, require_study_member, require_study_roles from app.crud import study as study_crud from app.schemas.study import StudyCreate, StudyRead, StudyUpdate router = APIRouter() @router.post("/", response_model=StudyRead, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_roles(["ADMIN"]))]) async def create_study( study_in: StudyCreate, db: AsyncSession = Depends(get_db_session), current_user=Depends(get_current_user), ) -> StudyRead: existing = await study_crud.get_by_code(db, study_in.code) if existing: raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Study code already exists") study = await study_crud.create(db, study_in, created_by=current_user.id) return study @router.get("/", response_model=list[StudyRead]) async def list_studies( skip: int = 0, limit: int = 100, db: AsyncSession = Depends(get_db_session), current_user=Depends(get_current_user), ) -> list[StudyRead]: if current_user.role == "ADMIN": studies = await study_crud.list_studies(db, skip=skip, limit=limit) else: studies = await study_crud.list_studies_for_user(db, current_user.id, skip=skip, limit=limit) return list(studies) @router.get("/{study_id}", response_model=StudyRead, dependencies=[Depends(require_study_member())]) async def get_study( study_id: uuid.UUID, db: AsyncSession = Depends(get_db_session), ) -> StudyRead: 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.patch( "/{study_id}", response_model=StudyRead, dependencies=[Depends(require_study_roles(["PM"]))], ) async def update_study( study_id: uuid.UUID, study_in: StudyUpdate, db: AsyncSession = Depends(get_db_session), ) -> StudyRead: study = await study_crud.get(db, study_id) if not study: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Study not found") updated = await study_crud.update(db, study, study_in) return updated