"""Map IlumError subclasses to HTTP status codes."""

from __future__ import annotations

from fastapi import Request
from fastapi.responses import JSONResponse

from ilum.api.models import ErrorResponse
from ilum.errors import (
    AuthError,
    ClusterConnectionError,
    HelmError,
    HelmTimeoutError,
    IlumError,
    ModuleError,
    ReleaseExistsError,
    ReleaseNotFoundError,
    ValuesError,
)

_ERROR_STATUS_MAP: dict[type[IlumError], int] = {
    ModuleError: 400,
    AuthError: 401,
    ReleaseNotFoundError: 404,
    ReleaseExistsError: 409,
    ValuesError: 422,
    HelmError: 502,
    ClusterConnectionError: 503,
    HelmTimeoutError: 504,
}


def status_for_error(exc: IlumError) -> int:
    """Return the HTTP status code for an IlumError subclass."""
    for cls in type(exc).__mro__:
        if cls in _ERROR_STATUS_MAP:
            return _ERROR_STATUS_MAP[cls]
    return 500


async def ilum_error_handler(_request: Request, exc: IlumError) -> JSONResponse:
    """FastAPI exception handler for IlumError."""
    status = status_for_error(exc)
    body = ErrorResponse(
        detail=str(exc),
        error_code=exc.error_code,
        suggestion=exc.suggestion,
    )
    return JSONResponse(status_code=status, content=body.model_dump())
