"""Webhook view for receiving provider events."""

import logging

from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import DetailView

from ..events import handle_events
from ..models.provider import MissiveProviderModel

logger = logging.getLogger(__name__)


@method_decorator(csrf_exempt, name="dispatch")
class WebhookView(DetailView):
    """Webhook view based on provider model."""

    model = MissiveProviderModel
    slug_field = "name"
    slug_url_kwarg = "provider"

    def post(self, request, *args, **kwargs):
        """Handle webhook POST request."""
        return self.handle_webhook(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        """Handle webhook GET request."""
        return self.handle_webhook(request, *args, **kwargs)

    def handle_webhook(self, request, *args, **kwargs):
        provider = self.get_object()
        missive_type = kwargs.get("missive_type")
        try:
            handle_events(request.body, provider=provider, missive_type=missive_type)
        except Exception as e:
            logger.error(f"Error handling webhook: {e}", exc_info=True)
        return HttpResponse(status=200)
