"""Route registration listener for webhook endpoints."""

from amsdal_server.apps.common.events.server import RouterSetupContext  # type: ignore[import-not-found]
from amsdal_utils.events import AsyncNextFn
from amsdal_utils.events import EventListener
from amsdal_utils.events import NextFn
from fastapi import APIRouter  # type: ignore[import-not-found]
from fastapi import Request

from amsdal_mail.webhooks.handler import SupportedESP
from amsdal_mail.webhooks.handler import webhook_handler


class WebhookRouterListener(EventListener[RouterSetupContext]):
    """Subscribes to RouterSetupEvent and registers the webhook route."""

    def handle(
        self,
        context: RouterSetupContext,
        next_fn: NextFn[RouterSetupContext],
    ) -> RouterSetupContext:
        from amsdal_mail.settings import mail_settings

        base_path = mail_settings.WEBHOOK_BASE_PATH

        router = APIRouter()

        @router.post(f'{base_path}/{{esp_name}}', include_in_schema=False)
        async def _webhook(esp_name: SupportedESP, request: Request) -> dict[str, object]:
            return await webhook_handler(esp_name, request)

        context.app.include_router(router)

        return next_fn(context)

    async def ahandle(
        self,
        context: RouterSetupContext,
        next_fn: AsyncNextFn[RouterSetupContext],
    ) -> RouterSetupContext:
        return self.handle(context, next_fn)  # type: ignore[arg-type,unused-ignore]
