from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver

from .cv_library import archive_previous_cv, index_seeker_cv
from .models import SeekerProfile


@receiver(pre_save, sender=SeekerProfile)
def preserve_previous_cv_on_replace(sender, instance, **kwargs):
    if not instance.pk or not instance.cv_file:
        return
    try:
        previous = SeekerProfile.objects.get(pk=instance.pk)
    except SeekerProfile.DoesNotExist:
        return
    if not previous.cv_file or not previous.cv_file.name:
        return
    new_name = instance.cv_file.name if instance.cv_file else ''
    if previous.cv_file.name != new_name:
        archive_previous_cv(previous, previous.cv_file)


@receiver(post_save, sender=SeekerProfile)
def index_cv_on_profile_save(sender, instance, **kwargs):
    if instance.cv_file and instance.cv_file.name:
        index_seeker_cv(instance)
