from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .models import NotificationTemplate
from .serializers import NotificationSerializer, NotificationTemplateSerializer
from .services import send_notification


class NotificationTemplateListCreateView(generics.ListCreateAPIView):
    queryset = NotificationTemplate.objects.all()
    serializer_class = NotificationTemplateSerializer


class NotificationTemplateRetrieveUpdateView(generics.RetrieveUpdateAPIView):
    queryset = NotificationTemplate.objects.all()
    serializer_class = NotificationTemplateSerializer


@api_view(['POST'])
def send_notification_view(request):
    data = request.data
    channel = data.get('channel')
    recipient = data.get('recipient')
    template_code = data.get('template_code')
    context = data.get('context', {})
    subject = data.get('subject')
    body = data.get('body')

    if not channel or not recipient:
        return Response({'detail': 'channel and recipient required'}, status=status.HTTP_400_BAD_REQUEST)

    res = send_notification(channel=channel, recipient=recipient, template_code=template_code, context=context, subject=subject, body=body, user=request.user if request.user.is_authenticated else None)
    return Response(res)
