import logging

from pyrogram import filters
from pyrogram.types import CallbackQuery, Message

from classes.callbacks import CallbackBan
from classes.pyroclient import PyroClient
from modules.utils import is_permitted

logger = logging.getLogger(__name__)


@PyroClient.on_callback_query(filters.regex(r"ban:[\s\S]*"))  # type: ignore
async def callback_ban(app: PyroClient, callback: CallbackQuery):
    group = await app.find_group(callback.message.chat.id)
    locale = group.select_locale(app, callback.message.from_user)

    if not (await is_permitted(app, group, callback=callback)):
        await callback.answer(
            app._("wrong_user", "callbacks", locale=locale), show_alert=True
        )
        return

    parsed = CallbackBan.from_callback(callback)

    user = await app.find_user(parsed.user_id, group.id)

    logger.info(
        "User %s has been marked as failed the captcha by %s",
        user.id,
        callback.from_user.id,
    )

    await user.set_mistakes(3)
    await user.set_failed(True)
    await callback.answer(
        app._("captcha_failed_force", "callbacks", locale=locale).format(
            user_id=user.id
        ),
        show_alert=True,
    )

    banned = await app.ban_chat_member(group.id, user.id)

    if isinstance(banned, Message):
        await banned.delete()

    await callback.message.delete()
    return
