import httpx
from fastapi import Request, Response

from app.config.settings import settings

# One shared async client for all forwarded requests
client = httpx.AsyncClient(base_url=settings.BACKEND_URL, timeout=30.0)


async def forward(request: Request, path: str) -> Response:
    """Forward the incoming request to Django and relay the response back."""
    headers = {}

    content_type = request.headers.get("content-type")
    if content_type:
        headers["Content-Type"] = content_type

    # Pass the user's token straight through — Django validates it
    authorization = request.headers.get("authorization")
    if authorization:
        headers["Authorization"] = authorization

    # Tell Django the real client IP
    headers["X-Forwarded-For"] = request.client.host if request.client else "unknown"

    body = await request.body()

    backend_response = await client.request(
        method=request.method,
        url=path,
        content=body if body else None,
        params=dict(request.query_params),
        headers=headers,
    )

    return Response(
        content=backend_response.content,
        status_code=backend_response.status_code,
        media_type=backend_response.headers.get("content-type"),
    )


async def close_client():
    await client.aclose()
