"""Router registration and the private admin boundary."""

from __future__ import annotations

from aiogram import Dispatcher, F, Router

from app.context import AppContext
from app.handlers import (
    admin_menu,
    admins,
    auto_delete,
    captions,
    channels,
    ingest,
    links,
    media,
    membership,
    posts,
    scheduling,
    settings,
    start,
    statistics,
)
from app.middlewares.access import AdminOnlyMiddleware
from app.middlewares.errors import handle_error

_ADMIN_ROUTERS = (
    admin_menu.router,
    media.router,
    captions.router,
    auto_delete.router,
    channels.router,
    membership.router,
    posts.router,
    links.router,
    scheduling.router,
    statistics.router,
    admins.router,
    settings.router,
)


def build_dispatcher(ctx: AppContext) -> Dispatcher:
    dispatcher = Dispatcher()
    dispatcher["ctx"] = ctx

    admin_root = Router(name="admin-root")
    admin_root.message.filter(F.chat.type == "private")
    admin_root.callback_query.filter(F.message.chat.type == "private")
    admin_root.message.middleware(AdminOnlyMiddleware(ctx.admins))
    admin_root.callback_query.middleware(AdminOnlyMiddleware(ctx.admins))
    admin_root.include_routers(*_ADMIN_ROUTERS)

    dispatcher.include_router(start.router)
    dispatcher.include_router(ingest.router)
    dispatcher.include_router(admin_root)
    dispatcher.errors.register(handle_error)
    return dispatcher


__all__ = ["build_dispatcher"]
