from typing import Awaitable, Callable

from fastapi import HTTPException, Request, Response

MiddlewareCallNext = Callable[[Request], Awaitable[Response]]


async def validate_json(
    request: Request, call_next: MiddlewareCallNext
) -> Response:
    # Only validate JSON for requests with a body
    if request.method in ("POST", "PUT", "PATCH"):
        # Only attempt JSON parsing when the client indicates a JSON content type.
        content_type = (request.headers.get("content-type") or "").lower()
        if "json" in content_type:
            try:
                # attempt to parse json body
                await request.json()
            except Exception:
                raise HTTPException(
                    status_code=400, detail="Invalid JSON payload")
    response = await call_next(request)
    return response
