import logging

from fastapi import APIRouter, Depends

from intranet.library.fastapi_csrf.src import csrf_exempt

from intranet.trip.src.api.depends import get_unit_of_work, only_for_tvm
from intranet.trip.src.api.schemas import NotificationSyncIn, EventIn

from intranet.trip.src.config import settings
from intranet.trip.src.logic.messenger import create_new_messages_from_aeroclub
from intranet.trip.src.logic.notifications import process_notification
from intranet.trip.src.unit_of_work import UnitOfWork


logger = logging.getLogger(__name__)
router = APIRouter()


@router.put('/sync')
@csrf_exempt
async def notification_about_message(
    notification_sync_in: NotificationSyncIn,
    _auth=Depends(only_for_tvm('trip')),
    uow: UnitOfWork = Depends(get_unit_of_work()),
):
    """
    Уведомление о получении нового сообщения в чате с аэроклубом
    """
    await create_new_messages_from_aeroclub(
        uow=uow,
        aeroclub_journey_id=notification_sync_in.aeroclub_journey_id,
        aeroclub_trip_id=notification_sync_in.aeroclub_trip_id,
    )
    return {}


@router.post('/event')
@csrf_exempt
async def trip_event(
    event_in: EventIn,
    _auth=Depends(only_for_tvm('trip')),
    uow: UnitOfWork = Depends(get_unit_of_work(read_only=True)),
):
    if settings.ENABLE_AEROCLUB_EVENT_HANDLING:
        await process_notification(uow, event_in)
    return {}
