"""Webhook HTTP handler for receiving ESP tracking events."""

from enum import StrEnum
from typing import Any

from amsdal_utils.events import EventBus

from amsdal_mail.events import EmailTrackingEvent
from amsdal_mail.webhooks.registry import WebhookRegistry


class SupportedESP(StrEnum):
    ses = 'ses'


async def webhook_handler(esp_name: SupportedESP, request: Any) -> dict[str, Any]:
    """Handle incoming webhook POST from ESP.

    Args:
        esp_name: Which ESP is sending the webhook (path parameter).
        request: FastAPI Request object.

    Returns:
        JSON response with status and count of processed events.
    """
    from fastapi import HTTPException  # type: ignore[import-not-found]

    parser = WebhookRegistry.get_parser(esp_name.value)
    if not parser:
        raise HTTPException(status_code=404, detail=f'No parser registered for ESP: {esp_name.value}')

    body = await request.body()
    headers = dict(request.headers)

    if not parser.verify(body, headers):
        raise HTTPException(status_code=403, detail='Webhook verification failed')

    events = parser.parse(body, headers)

    for event in events:
        await EventBus.aemit(EmailTrackingEvent, event)

    return {'status': 'ok', 'events_processed': len(events)}
