import json
import logging

from aiohttp import web
from marshmallow import ValidationError

from maps_adv.adv_store.lib.api_provider.exceptions import (
    EXCEPTION_ERROR_CODES,
    DomainException,
)
from maps_adv.adv_store.api.proto.error_pb2 import Error

logger = logging.getLogger(__name__)


@web.middleware
async def handle_domain_exception(request, handler):
    try:
        return await handler(request)
    except DomainException as exc:
        logger.exception(exc)
        error = Error(code=EXCEPTION_ERROR_CODES[type(exc)], description=str(exc))
        return web.Response(status=400, body=error.SerializeToString())


@web.middleware
async def handle_validation_exception(request, handler):
    try:
        return await handler(request)
    except ValidationError as exc:
        logger.error("Serialization error: %s", exc.normalized_messages())
        error = Error(
            code=Error.INVALID_INPUT_DATA, description=json.dumps(exc.messages)
        )
        return web.Response(status=400, body=error.SerializeToString())
