from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from quotation.models import Invoice, Customer_Payment, Order,Order_Item,Technician_Assigned_Order_Item
from technician.models import Job_Time,Notification
from geopy.geocoders import Nominatim
from technician.models import Technician_Assigned_Order_Item, Notification
from django.utils import timezone
from product.models import SerialNumber,Product
from service.models import Question,Answer,Checklist
# from technician.models import send_notification_to_technician
from django.contrib.messages import success
from celery import shared_task
from django.db.models import Sum
from decimal import Decimal

@receiver(post_save, sender=Question)
def after_question_created(sender, instance, created, **kwargs):
    print(f"Signal received for instance id: {instance.id}, created: {created}")
    if created:
        technician_assigned_jobs=Technician_Assigned_Order_Item.objects.filter(customer_signature_required = 1)
        print(technician_assigned_jobs)
        for technician_assigned_job in technician_assigned_jobs :
            if str(instance.checklist.type) == "3":
                print(instance)
                try:
                    obj, created = Answer.objects.get_or_create(
                        technician_assigned_job=technician_assigned_job,
                        question=instance,
                        defaults={'is_signature': True}
                    )
                
                    if created:
                        print("✅ Answer created")
                    else:
                        print("⚠️ Already exists")
                
                except Exception as e:
                    print("❌ ERROR:", e)
                
        technician_assigned_jobs=Technician_Assigned_Order_Item.objects.filter(job_status__lt = 4)
        print(technician_assigned_jobs)
        for technician_assigned_job in technician_assigned_jobs :
            if str(instance.checklist.type) == "1" :
                Answer.objects.create(
                technician_assigned_job=technician_assigned_job,
                question=instance,
                is_installation=True
            )
            else:
                Answer.objects.create(
                technician_assigned_job=technician_assigned_job,
                question=instance,
            )




    
 