from __future__ import annotations

from adapter.matrix.store import clear_pending_confirm, get_pending_confirm
from core.protocol import IncomingCallback, OutgoingMessage


def make_handle_confirm(store=None):
    async def handle_confirm(
        event: IncomingCallback, auth_mgr, platform, chat_mgr, settings_mgr
    ) -> list:
        if store is None:
            return [OutgoingMessage(chat_id=event.chat_id, text="Нет ожидающих подтверждений.")]

        room_id = event.payload.get("room_id")
        pending = None
        if room_id:
            pending = await get_pending_confirm(store, event.user_id, room_id)
        if not pending:
            pending = await get_pending_confirm(store, event.chat_id)
        if not pending:
            return [OutgoingMessage(chat_id=event.chat_id, text="Нет ожидающих подтверждений.")]

        description = pending.get("description", "действие")
        if room_id:
            await clear_pending_confirm(store, event.user_id, room_id)
        else:
            await clear_pending_confirm(store, event.chat_id)

        return [OutgoingMessage(chat_id=event.chat_id, text=f"Подтверждено: {description}")]

    return handle_confirm


def make_handle_cancel(store=None):
    async def handle_cancel(
        event: IncomingCallback, auth_mgr, platform, chat_mgr, settings_mgr
    ) -> list:
        if store is None:
            return [OutgoingMessage(chat_id=event.chat_id, text="Нет ожидающих подтверждений.")]

        room_id = event.payload.get("room_id")
        pending = None
        if room_id:
            pending = await get_pending_confirm(store, event.user_id, room_id)
        if not pending:
            pending = await get_pending_confirm(store, event.chat_id)
        if not pending:
            return [OutgoingMessage(chat_id=event.chat_id, text="Нет ожидающих подтверждений.")]

        if room_id:
            await clear_pending_confirm(store, event.user_id, room_id)
        else:
            await clear_pending_confirm(store, event.chat_id)
        return [OutgoingMessage(chat_id=event.chat_id, text="Действие отменено.")]

    return handle_cancel
