from __future__ import annotations from typing import Annotated from fastapi import APIRouter, Depends, HTTPException, Query, status from app.api.deps import require_admin from app.core.database import get_connection from app.core.schemas import AdminOrderUpdateRequest, OrderDetailOut, OrderSummaryOut, UserProfile from app.services import repository router = APIRouter(prefix="/api/admin", tags=["admin"]) @router.get("/orders", response_model=list[OrderSummaryOut]) def list_orders( _: Annotated[UserProfile, Depends(require_admin)], status_text: str | None = Query(default=None, alias="status"), category: str | None = Query(default=None), urgency: str | None = Query(default=None), ) -> list[dict[str, str]]: with get_connection() as connection: return repository.list_orders(connection, status=status_text, category=category, urgency=urgency) @router.get("/orders/{order_id}", response_model=OrderDetailOut) def get_order(order_id: int, _: Annotated[UserProfile, Depends(require_admin)]) -> dict[str, str]: with get_connection() as connection: detail = repository.get_order_detail(connection, order_id) if detail is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="order_not_found") return detail @router.patch("/orders/{order_id}") def update_order( order_id: int, payload: AdminOrderUpdateRequest, admin: Annotated[UserProfile, Depends(require_admin)], ) -> dict[str, str]: with get_connection() as connection: try: repository.update_order(connection, order_id, admin, payload) except KeyError as error: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(error)) from error except ValueError as error: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(error)) from error return {"status": "ok"} @router.get("/stats") def get_stats(_: Annotated[UserProfile, Depends(require_admin)]) -> dict[str, object]: with get_connection() as connection: return repository.get_stats(connection) @router.post("/orders/{order_id}/accept-rework") def accept_rework( order_id: int, admin: Annotated[UserProfile, Depends(require_admin)], ) -> dict[str, str]: with get_connection() as connection: try: repository.accept_rework(connection, order_id, admin) except KeyError as error: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(error)) from error except ValueError as error: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(error)) from error return {"status": "ok"} @router.post("/orders/{order_id}/reject-rework") def reject_rework( order_id: int, admin: Annotated[UserProfile, Depends(require_admin)], ) -> dict[str, str]: with get_connection() as connection: try: repository.reject_rework(connection, order_id, admin) except KeyError as error: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(error)) from error except ValueError as error: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(error)) from error return {"status": "ok"}