from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import datetime, timedelta
from django.db.models import Q
from reservation.models import Reservation
from patient.models import  Patient
# from core.management.utils import send_whatsapp_message
from waapi.utils import send_whatsapp
import time
import logging

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = 'Sending follow-up messages to patients'

    def handle(self, *args, **options):
        self.stdout.write("Starting to send follow-up messages...")

        self.send_completed_patients_messages()

        self.send_no_service_messages()

        self.stdout.write(self.style.SUCCESS('✅ Follow-up messages have been sent.'))

    def send_completed_patients_messages(self):
        last_month = timezone.now() - timedelta(days=30)

        completed_reservations = Reservation.objects.filter(
            status='completed',
            updated_at__gte=last_month
        ).select_related('patient', 'service')

        for reservation in completed_reservations:
            patient = reservation.patient
            service_name = reservation.service.name if reservation.service else "service"

            message = f"""
Hi Dear {patient.get_full_name()} 🌸

We hope you were satisfied with the {service_name} service you received last month.
Your health is important to us. We are at your service if you need consultation or new services.
📞 For appointment scheduling: {settings.MANAGER_PHONE}
            """.strip()
            # time.sleep(2)
            success = send_whatsapp(patient.phone_number, message)
            if success:
                self.stdout.write(f"✅ Message sent to {patient.get_full_name()}")
            else:
                self.stdout.write(f"❌ Error in sending to {patient.get_full_name()}")

    def send_no_service_messages(self):

        patients_without_reservation = Patient.objects.filter(
            patients_reservation__isnull=True
        )

        for patient in patients_without_reservation:
            message = f"""
Hello dear {patient.get_full_name()} 🌟

Thank you for being a member of our team.

We are ready to offer the best medical and beauty services to you dear ones:
• Specialized consultation
• Medical services
• Beauty services
📞 For more information and appointment scheduling: [phone number]
            """.strip()
            time.sleep(2)
            success = send_whatsapp(patient.phone_number, message)
            if success:
                self.stdout.write(f"✅ Encouraging message sent to {patient.get_full_name()}")