import requests
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.conf import settings
from django.utils import timezone
import logging

from .models import WhatsAppNotification
from .serializers import WhatsAppNotificationSerializer

logger = logging.getLogger(__name__)

class NotificationViewSet(viewsets.ModelViewSet):
    queryset = WhatsAppNotification.objects.all()
    serializer_class = WhatsAppNotificationSerializer
    permission_classes = [IsAuthenticated]
    
    @action(detail=False, methods=['post'])
    def send(self, request):
        """POST /api/notifications/send/"""
        phone_number = request.data.get('phone_number')
        message = request.data.get('message')
        notification_type = request.data.get('notification_type', 'other')
        
        if not phone_number or not message:
            return Response(
                {'error': 'phone_number y message son requeridos'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # Crear registro de notificación
        notification = WhatsAppNotification.objects.create(
            phone_number=phone_number,
            message=message,
            notification_type=notification_type,
            status='pending'
        )
        
        try:
            # Enviar por WhatsApp
            headers = {
                "Authorization": f"Bearer {settings.WHATSAPP_TOKEN}",
                "Content-Type": "application/json",
            }
            
            payload = {
                "messaging_product": "whatsapp",
                "recipient_type": "individual",
                "to": phone_number,
                "type": "text",
                "text": {
                    "preview_url": False,
                    "body": message
                }
            }
            
            api_url = f"https://graph.instagram.com/v18.0/{settings.WHATSAPP_PHONE_ID}/messages"
            response = requests.post(api_url, json=payload, headers=headers, timeout=10)
            response.raise_for_status()
            
            result = response.json()
            message_id = result.get("messages", [{}])[0].get("id")
            
            # Actualizar registro
            notification.message_id = message_id
            notification.status = 'sent'
            notification.sent_at = timezone.now()
            notification.save()
            
            logger.info(f"WhatsApp message sent to {phone_number}")
            
        except requests.exceptions.RequestException as e:
            notification.status = 'failed'
            notification.error_message = str(e)
            notification.save()
            logger.error(f"Error sending WhatsApp: {str(e)}")
        
        serializer = self.get_serializer(notification)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    
    @action(detail=False, methods=['get'])
    def history(self, request):
        """GET /api/notifications/history/"""
        notifications = WhatsAppNotification.objects.all()
        serializer = self.get_serializer(notifications, many=True)
        return Response(serializer.data)