# apps/reviews/management/commands/clean_duplicates.py
from django.core.management.base import BaseCommand
from django.db.models import Count
from apps.reviews.models import ReviewLink


class Command(BaseCommand):
    help = "Clean duplicate ReviewLinks by (tour, customer_email). Keeps the most recent one."

    def handle(self, *args, **kwargs):
        duplicates = (
            ReviewLink.objects.values("tour_id", "customer_email")
            .annotate(count=Count("id"))
            .filter(count__gt=1)
        )

        if not duplicates:
            self.stdout.write(self.style.SUCCESS("No duplicates found."))
            return

        for dup in duplicates:
            links = (
                ReviewLink.objects.filter(
                    tour_id=dup["tour_id"], customer_email=dup["customer_email"]
                )
                .order_by("-created_at")
            )
            keep = links.first()
            to_delete = links[1:]

            deleted_count = to_delete.count()
            if deleted_count:
                to_delete.delete()
                self.stdout.write(
                    self.style.WARNING(
                        f"Kept link {keep.id} for {dup['customer_email']} (tour {dup['tour_id']}), "
                        f"deleted {deleted_count} duplicate(s)."
                    )
                )

        self.stdout.write(self.style.SUCCESS("Duplicate cleanup complete."))
