from typing import Optional

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

from maps_adv.geosmb.tuner.proto.errors_pb2 import Error
from maps_adv.geosmb.tuner.server.lib.exceptions import UnknownBizId

__all__ = ["handle_validation_errors", "handle_domain_errors"]


@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_domain_errors(req: Request, handler) -> Response:
    status, code, description = 400, None, None
    try:
        return await handler(req)
    except UnknownBizId as exc:
        code = Error.UNKNOWN_BIZ_ID
        description = _list_to_str(exc.args)

    error = Error(code=code)
    if description is not None:
        error.description = description

    return Response(status=status, body=error.SerializeToString())


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


def _list_to_str(data: list) -> Optional[str]:
    return ", ".join([str(e) for e in data]) if data else None
