from aiohttp.web import Request, Response, middleware
from marshmallow import ValidationError

from maps_adv.geosmb.promoter.proto.errors_pb2 import Error
from maps_adv.geosmb.promoter.server.lib.exceptions import UnknownLead

__all__ = ["handle_validation_errors", "handle_application_errors"]


def _dict_to_str(data: dict, separator=": ") -> str:
    return ", ".join(f"{field}{separator}{data[field]}" for field in sorted(data))


@middleware
async def handle_validation_errors(req: Request, handler) -> Response:
    try:
        return await handler(req)
    except ValidationError as exc:
        if isinstance(exc.messages, dict):
            description = _dict_to_str(exc.messages)
        else:
            description = ", ".join(sorted(exc.messages))

        error = Error(code=Error.VALIDATION_ERROR, description=description)
        return Response(status=400, body=error.SerializeToString())


@middleware
async def handle_application_errors(req: Request, handler) -> Response:
    try:
        return await handler(req)
    except UnknownLead as exc:
        error = Error(code=Error.UNKNOWN_LEAD, description=exc.args[0])
        return Response(status=404, body=error.SerializeToString())
