from __future__ import annotations

from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework.request import Request

from sentry import options
from sentry.models import Organization

from .base import GithubWebhookBase
from .events import InstallationEventWebhook, InstallationRepositoryEventWebhook, PushEventWebhook


class GithubIntegrationsWebhookEndpoint(GithubWebhookBase):
    _handlers = {
        "push": PushEventWebhook,
        "installation": InstallationEventWebhook,
        "installation_repositories": InstallationRepositoryEventWebhook,
    }

    @method_decorator(csrf_exempt)
    def dispatch(self, request: Request, *args, **kwargs) -> HttpResponse:
        if request.method != "POST":
            return HttpResponse(status=405)

        return super().dispatch(request, *args, **kwargs)

    def get_secret(self, organization: Organization) -> str | None:
        return options.get("github.integration-hook-secret")

    def post(self, request: Request) -> HttpResponse:
        return self.handle(request)
