# tasks.py
from celery import shared_task
from django.utils import timezone
from Subscriptions.automate import Automate_RF_Register, updateStateMachine
from .models import RegistrationForm
from GestionMessagerie.models import Messagerie
from N3wtSchool import settings, bdd
import requests
import logging
logger = logging.getLogger(__name__)

@shared_task
def check_for_signature_deadlines():
    now = timezone.now()
    deadline = now - timezone.timedelta(days=settings.EXPIRATION_DI_NB_DAYS)
    # deadline = now - timezone.timedelta(seconds=settings.EXPIRATION_DI_NB_DAYS)

    dossiers_en_attente = RegistrationForm.objects.filter(etat=RegistrationForm.RegistrationFormStatus.DI_ENVOYE, dateMAJ__lt=deadline)

    for dossier in dossiers_en_attente:
        send_notification(dossier)

def send_notification(dossier):
    logger.debug(f'Dossier en attente.... {dossier} - Positionnement à l\'état TO_BE_FOLLOWED_UP')

    # Changer l'état de l'automate
    updateStateMachine(dossier, 'EVENT_FOLLOW_UP')

    url = settings.URL_DJANGO + 'GestionMessagerie/message'

    destinataires = dossier.eleve.profiles.all()
    for destinataire in destinataires:
        message = {
            "objet": "[RELANCE]",
            "destinataire" : destinataire.id,
            "corpus": "RELANCE pour le dossier d'inscription"
        }

        response = requests.post(url, json=message)

    # subject = f"Dossier d'inscription non signé - {dossier.objet}"
    # message = f"Le dossier d'inscription avec l'objet '{dossier.objet}' n'a pas été signé depuis {dossier.created_at}."
    # send_mail(subject, message, settings.EMAIL_HOST_USER, [dossier.destinataire.email])
