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, require_study_roles from app.crud import audit as audit_crud from app.crud import imp_batch as batch_crud from app.crud import study as study_crud from app.schemas.imp import BatchCreate, BatchRead, BatchUpdate 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=BatchRead, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_study_roles(["PM", "IMP"]))], ) async def create_batch( study_id: uuid.UUID, batch_in: BatchCreate, db: AsyncSession = Depends(get_db_session), current_user=Depends(get_current_user), ) -> BatchRead: await _ensure_study_exists(db, study_id) try: batch = await batch_crud.create_batch(db, study_id, batch_in) except ValueError as exc: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc await audit_crud.log_action( db, study_id=study_id, entity_type="imp_batch", entity_id=batch.id, action="CREATE_IMP_BATCH", detail=f"IMP batch {batch.batch_no} created", operator_id=current_user.id, operator_role=current_user.role, ) return BatchRead.model_validate(batch) @router.get( "/", response_model=list[BatchRead], dependencies=[Depends(require_study_member())], ) async def list_batches( study_id: uuid.UUID, product_id: uuid.UUID | None = None, status_filter: str | None = None, db: AsyncSession = Depends(get_db_session), ) -> list[BatchRead]: await _ensure_study_exists(db, study_id) batches = await batch_crud.list_batches(db, study_id, product_id=product_id, status=status_filter) return [BatchRead.model_validate(b) for b in batches] @router.patch( "/{batch_id}", response_model=BatchRead, dependencies=[Depends(require_study_roles(["PM", "IMP"]))], ) async def update_batch( study_id: uuid.UUID, batch_id: uuid.UUID, batch_in: BatchUpdate, db: AsyncSession = Depends(get_db_session), current_user=Depends(get_current_user), ) -> BatchRead: await _ensure_study_exists(db, study_id) batch = await batch_crud.get_batch(db, batch_id) if not batch or batch.study_id != study_id: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Batch not found") updated = await batch_crud.update_batch(db, batch, batch_in) await audit_crud.log_action( db, study_id=study_id, entity_type="imp_batch", entity_id=batch_id, action="UPDATE_IMP_BATCH", detail=f"IMP batch {batch_id} updated", operator_id=current_user.id, operator_role=current_user.role, ) return BatchRead.model_validate(updated)