from aiohttp.web import Request, Response, json_response, middleware

from smb.common.aiotvm.lib.exceptions import BaseTvmException
from maps_adv.geosmb.cleaner.server.lib.exceptions import (
    NoPassportUidException,
    NoUserTicketException,
    ValidationException,
)


@middleware
async def handle_validation_errors(req: Request, handler) -> Response:
    try:
        return await handler(req)
    except ValidationException as exc:
        return Response(status=400, text=str(exc))
    except NoUserTicketException:
        return _make_error_response(
            code="missed_user_ticket", message="TVM user ticket is missed"
        )


@middleware
async def handle_domain_errors(req: Request, handler) -> Response:
    try:
        return await handler(req)
    except BaseTvmException as exc:
        return _make_error_response(code="bad_user_ticket", message=str(exc))
    except NoPassportUidException:
        return _make_error_response(
            code="no_passport_uid", message="No passport uid for TVM user ticket"
        )


def _make_error_response(code: str, message: str) -> Response:
    return json_response(
        {"status": "error", "errors": [{"code": code, "message": message}]}
    )
