"""Admin-only access control for every command and callback."""

from __future__ import annotations

import logging
from collections.abc import Awaitable, Callable
from typing import Any

from aiogram import BaseMiddleware
from aiogram.types import CallbackQuery, Message, TelegramObject

logger = logging.getLogger(__name__)

PUBLIC_COMMANDS = {"/start", "/help", "/id"}
PUBLIC_CALLBACKS = {"menu:home", "menu:help"}
DENIED_TEXT = "⛔️ این بخش فقط برای مدیران ربات در دسترس است."


def _command_of(text: str | None) -> str | None:
    if not text or not text.startswith("/"):
        return None
    return text.split(maxsplit=1)[0].split("@", 1)[0].lower()


class AccessMiddleware(BaseMiddleware):
    """Reject non-administrators before any handler-side effects run."""

    def __init__(self, admin_ids: list[int] | tuple[int, ...]) -> None:
        self.admin_ids = frozenset(int(item) for item in admin_ids)

    async def __call__(
        self,
        handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
        event: TelegramObject,
        data: dict[str, Any],
    ) -> Any:
        user = getattr(event, "from_user", None)
        if user is not None and user.id in self.admin_ids:
            return await handler(event, data)

        if isinstance(event, Message):
            command = _command_of(event.text)
            if command in PUBLIC_COMMANDS:
                return await handler(event, data)
            if command is not None:
                await event.answer(DENIED_TEXT, parse_mode=None)
            return None

        if isinstance(event, CallbackQuery):
            if event.data in PUBLIC_CALLBACKS:
                return await handler(event, data)
            logger.warning(
                "rejected non-admin callback from user %s",
                getattr(user, "id", "unknown"),
            )
            await event.answer(DENIED_TEXT, show_alert=True)
            return None

        return None
