# fastapi.py
from fastapi.responses import JSONResponse
from sqlalchemy.exc import DBAPIError, OperationalError, StatementError


async def database_error_middleware(request, call_next):
    try:
        return await call_next(request)

    except OperationalError:
        return JSONResponse(
            status_code=503,
            content={"detail": "Database non disponibile"},
        )

    except StatementError:
        return JSONResponse(
            status_code=503,
            content={"detail": "Errore query"},
        )

    except DBAPIError:
        return JSONResponse(
            status_code=503,
            content={"detail": "Errore database"},
        )