import logging
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework import viewsets, status

from apps.appointments.serializers import (
    GHLAppointmentInputSerializer,
    WebhookSuccessSerializer
)
from apps.appointments.services import GHLAppointmentService


logger = logging.getLogger(__name__)


class AppointmentWebhookViewSet(viewsets.ViewSet):
    permission_classes = [AllowAny]
    authentication_classes = []

    @action(
        detail=False,
        methods=["post"],
        url_path="appointment-with-company",
    )
    def book_appointment_with_company(self, request):
        """
        Webhook endpoint to book appointment using a company identifier.
        """

        serializer = GHLAppointmentInputSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        try:
            GHLAppointmentService.book_ghl_appointment(
                serializer.validated_data
            )
        except ValueError as ve:
            return Response(
                WebhookSuccessSerializer(
                    {"message": str(ve)}
                ).data, status=status.HTTP_400_BAD_REQUEST
            )
        except Exception as exc:
            logger.exception(
                "Failed booking GHL appointment: %s",
                exc
            )
            return Response(
                WebhookSuccessSerializer(
                    {"message": "Failed to book appointment"}
                ).data, status=status.HTTP_400_BAD_REQUEST
            )

        return Response(
            WebhookSuccessSerializer(
                {"message": "Appointment booked successfully"}
            ).data, status=status.HTTP_200_OK
        )
