"""
Safe error handler for FastAPI.

Logs full error details internally but returns generic messages to clients
to prevent information disclosure.
"""

import logging
from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse

logger = logging.getLogger(__name__)


async def safe_exception_handler(request: Request, exc: Exception) -> JSONResponse:
    """
    Handle unhandled exceptions safely.

    - Logs full error details with context for debugging
    - Returns generic error message to client (prevents info disclosure)
    - Preserves HTTPException details (those are intended for clients)
    """

    # Extract context from request state
    user_id = getattr(request.state, "user", None)
    user_id_str = str(user_id.id) if user_id and hasattr(user_id, "id") else "anonymous"

    # Log full error details internally
    logger.error(
        f"Unhandled exception on {request.method} {request.url.path}",
        exc_info=True,
        extra={
            "user_id": user_id_str,
            "method": request.method,
            "path": request.url.path,
            "client_host": request.client.host if request.client else None,
        },
    )

    # If it's an HTTPException, return it as-is (these are intentional)
    if isinstance(exc, HTTPException):
        return JSONResponse(
            status_code=exc.status_code,
            content={"detail": exc.detail},
        )

    # For all other exceptions, return generic message
    return JSONResponse(
        status_code=500,
        content={
            "detail": "An internal error occurred. Please contact support if the problem persists."
        },
    )
