"""Signal handlers for courses app."""
from django.db.models.signals import pre_save
from django.dispatch import receiver

from apps.courses.models import COURSE_PRICE_FIELDS, Course, CoursePricingHistory


def _fmt(value):
    if value is None:
        return ''
    return str(value)


@receiver(pre_save, sender=Course)
def log_course_pricing_changes(sender, instance, **kwargs):
    """Write CoursePricingHistory rows when price-related fields change."""
    if not instance.pk:
        return
    try:
        previous = Course.objects.get(pk=instance.pk)
    except Course.DoesNotExist:
        return

    actor = getattr(instance, '_pricing_changed_by', None)
    for field in COURSE_PRICE_FIELDS:
        old = getattr(previous, field)
        new = getattr(instance, field)
        if old != new:
            CoursePricingHistory.objects.create(
                course_id=instance.pk,
                field_changed=field,
                old_price=_fmt(old),
                new_price=_fmt(new),
                changed_by=actor if getattr(actor, 'pk', None) else None,
            )
