from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver

from core_runtime.services import OutboxService
from .constants import MatchStatus
from .models import Match


@receiver(pre_save, sender=Match)
def remember_previous_match_status(sender, instance, **kwargs):
    if not instance.pk:
        instance._ftg_previous_status = None
        return
    instance._ftg_previous_status = sender.objects.filter(pk=instance.pk).values_list("status", flat=True).first()


@receiver(post_save, sender=Match)
def publish_match_status_transition(sender, instance, created, **kwargs):
    previous = getattr(instance, "_ftg_previous_status", None)
    if created or previous == instance.status:
        return
    event_map = {
        MatchStatus.IN_PROGRESS: "match.started",
        MatchStatus.COMPLETED: "match.completed",
        MatchStatus.CANCELLED: "match.cancelled",
    }
    event_type = event_map.get(instance.status)
    if not event_type:
        return
    payload = {
        "match_id": str(instance.pk),
        "fixture_id": str(instance.fixture_id),
        "previous_status": previous,
        "status": instance.status,
        "home_score": instance.home_score,
        "away_score": instance.away_score,
        "scheduled_at": instance.scheduled_at.isoformat() if instance.scheduled_at else None,
        "started_at": instance.started_at.isoformat() if instance.started_at else None,
        "completed_at": instance.completed_at.isoformat() if instance.completed_at else None,
    }
    OutboxService.enqueue(
        topic="matches.lifecycle",
        event_type=event_type,
        aggregate_type="Match",
        aggregate_id=instance.pk,
        deduplication_key=f"match:{instance.pk}:status:{instance.status}",
        payload=payload,
    )
