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

from maps_adv.geosmb.marksman.server.lib.exceptions import (
    BizNotAdded,
    BizNotFound,
    MarksmanException,
    NoOrgInfo,
    OrgWithoutCounter,
)

__all__ = ["handle_domain_errors", "handle_validation_errors"]


domain_exc_to_err_str = {
    BizNotFound: "BIZ_NOT_FOUND",
    NoOrgInfo: "NO_ORG_INFO",
    OrgWithoutCounter: "NO_COUNTER",
}


@middleware
async def handle_validation_errors(req: Request, handler) -> Response:
    try:
        return await handler(req)
    except ValidationError as exc:
        return json_response(exc.messages, status=400)


@middleware
async def handle_domain_errors(req: Request, handler) -> Response:
    try:
        return await handler(req)
    except BizNotAdded:
        return Response(status=404)
    except MarksmanException as exc:
        err_str = domain_exc_to_err_str[type(exc)]
        return json_response({"error": err_str}, status=400)
