from fastapi import APIRouter, Depends, File, HTTPException, UploadFile from fastapi.security import OAuth2PasswordBearer from pydantic import ValidationError from services.person_report_service import PersonReportService from models.schemas import PersonReportCreate, PersonReportUpdate, PersonReportResponse, UserResponse from config.database import get_db from typing import Optional from services.auth_service import AuthService router = APIRouter() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/token") @router.post("/", status_code=201) async def create_report( report: str, # Le champ report est reçu sous forme de chaîne JSON image_file: Optional[UploadFile] = File(None), # L'image est facultative db: get_db = Depends(), token: str = Depends(oauth2_scheme) ): try: # Valider et convertir la chaîne JSON en objet PersonReportCreate report_data = PersonReportCreate.model_validate_json(report) except ValidationError as e: raise HTTPException(status_code=422, detail=f"Invalid report data: {e}") # Appeler le service pour traiter le rapport try: created_report = await PersonReportService.create_report(report_data, db, image_file, token) except Exception as e: raise HTTPException(status_code=500, detail=f"An error occurred while creating the report: {str(e)}") return created_report @router.put("/{report_id}") async def update_report(report_id: int, report: PersonReportUpdate, db=Depends(get_db)): return await PersonReportService.update_report(report_id, report, db) @router.get("/{report_id}") async def get_report(report_id: int, db=Depends(get_db)): return await PersonReportService.get_report(report_id, db) @router.get("/", response_model=list[PersonReportResponse]) async def list_reports(status: Optional[str] = None, db=Depends(get_db)): return await PersonReportService.list_reports(status, db) @router.delete("/{report_id}", status_code=204) async def delete_report(report_id: int, db=Depends(get_db), current_user: UserResponse = Depends(AuthService.get_current_user)): return await PersonReportService.delete_report(report_id, db, current_user)