from aiogram import Router
from aiogram.types import Message
from aiogram.fsm.context import FSMContext
from bot.data.topic_map import user_topic_map
from bot.keyboards import decision_keyboard
from bot.states.union_states import UnionStates
from bot.utils import status_clear
from configs import ImportantID

router: Router = Router(name="union_handlers")



@router.message(UnionStates.waiting_for_union)
async def handle_union(message: Message, state: FSMContext) -> None:
    await message.answer("Спасибо! Ваше сообщение отправлено.")

    user = message.from_user
    user_id = user.id
    msg_type = "union"
    text = f"<b>СОЮЗ</b>\n\n{message.html_text}"

    key = (user_id, msg_type)

    if key in user_topic_map:
        thread_id = user_topic_map[key]
    else:
        topic = await message.bot.create_forum_topic(
            chat_id=ImportantID.SUPPORT_CHAT_ID,
            name=f"Сообщение от {user.full_name}"
        )
        thread_id = topic.message_thread_id
        user_topic_map[key] = thread_id

    await message.bot.send_message(
        chat_id=ImportantID.SUPPORT_CHAT_ID,
        message_thread_id=724,
        text=text,
        parse_mode="HTML",
        reply_markup=decision_keyboard(thread_id, "union")
    )

    await status_clear(message=message, state=state)

