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


def make_tenant_session_dep(cfg):
    async def _dep(request: Request):
        async for _ in cfg.get_db_session(request):
            yield cfg.current_session()
    return _dep


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

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

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

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