# app/core/error_handlers.py
import logging
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from app.core.api_response import err

logger = logging.getLogger(__name__)

def register_exception_handlers(app: FastAPI) -> None:
    """
    Plug this once in main.py to standardize ALL error responses as:
    { "code": <int>, "data": [], "message": "<text>" }
    """

    @app.exception_handler(HTTPException)
    async def http_exception_handler(request: Request, exc: HTTPException):
        # Use the detail as message
        message = exc.detail if isinstance(exc.detail, str) else "HTTP error"
        return err(message=message, code=exc.status_code)

    @app.exception_handler(StarletteHTTPException)
    async def starlette_http_exception_handler(request: Request, exc: StarletteHTTPException):
        # Handles 404 Not Found, 405 Method Not Allowed, etc. from Starlette
        message = exc.detail if isinstance(exc.detail, str) else "HTTP error"
        return err(message=message, code=exc.status_code)

    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Request, exc: RequestValidationError):
        # Flatten validation errors into a readable message + return full list in data
        message = "Validation failed"
        return err(message=message, code=422, data=exc.errors())

    @app.exception_handler(Exception)
    async def unhandled_exception_handler(request: Request, exc: Exception):
        # Last-resort handler – include the exception text per your requirement
        logger.exception("Unhandled exception: %s", exc)
        return err(message=str(exc), code=500)
