import asyncio
import logging
from typing import Callable

from intranet.trip.ext_api.src.config import settings


logger = logging.getLogger(__name__)


async def notification_action(action: Callable, **kwargs):
    if settings.ENABLE_B2B:
        exceptions = await asyncio.gather(
            action(**kwargs),
            action(is_b2b=True, **kwargs),
            return_exceptions=True,
        )
        if all([isinstance(exception, Exception) for exception in exceptions]):
            exception = min(exceptions, key=lambda err: getattr(err, 'status_code', 404))
            raise exception
    else:
        await action(**kwargs)
