"""
Domain error -> HTTPException translation helper.

Used by route handlers to keep services HTTP-agnostic while still giving
FastAPI the status codes it needs. Routes wrap their service calls with
the ``translate_domain_errors()`` context manager:

    with translate_domain_errors():
        return service.create(request)

The helper catches ``compliance.domain.DomainError`` subclasses and
re-raises them as ``fastapi.HTTPException`` with the appropriate status.
"""

from contextlib import contextmanager
from typing import Iterator

from fastapi import HTTPException

from compliance.domain import (
    ConflictError,
    DomainError,
    NotFoundError,
    PermissionError as DomainPermissionError,
    ValidationError,
)


@contextmanager
def translate_domain_errors() -> Iterator[None]:
    """Translate domain exceptions raised inside the block into HTTPException."""
    try:
        yield
    except NotFoundError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    except ConflictError as exc:
        raise HTTPException(status_code=409, detail=str(exc)) from exc
    except ValidationError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    except DomainPermissionError as exc:
        raise HTTPException(status_code=403, detail=str(exc)) from exc
    except DomainError as exc:
        raise HTTPException(status_code=500, detail=str(exc)) from exc
