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.anketa_states import StartForm
from configs import ImportantID

router = Router(name="form_handlers")

TOPIC_TYPE = "anketa"

@router.message(StartForm.waiting_for_application)
async def handle_application(message: Message, state: FSMContext):
    await state.clear()
    await message.answer("Спасибо! Ваша анкета отправлена на рассмотрение!")

    user = message.from_user
    user_id = user.id
    if user.username:
        users = f' от @{user.username}'
    else:
        users = ''
    text = f'<b><a href="tg://user?id={user_id}">Анкета{users}</a></b>\n\n{message.html_text}'

    key = (user_id, TOPIC_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=thread_id,
        text=text,
        reply_markup=decision_keyboard(thread_id, TOPIC_TYPE)  # <--- Передаём оба аргумента
    )


