from django.core.management.base import BaseCommand
from apparel.models import ApparelRequest
from django.db.models import Max

class Command(BaseCommand):
    help = 'Removes duplicate apparel requests, keeping only the most recent one for each user'

    def handle(self, *args, **options):
        # Get all registered users who have submitted apparel requests
        user_ids = ApparelRequest.objects.values_list('registered_user_id', flat=True).distinct()
        
        # Count before deduplication
        total_before = ApparelRequest.objects.count()
        self.stdout.write(f"Total apparel requests before deduplication: {total_before}")
        
        # For each user, keep only the most recent request
        duplicates_removed = 0
        for user_id in user_ids:
            if user_id is None:
                continue  # Skip null user_ids
                
            # Get all requests for this user
            user_requests = ApparelRequest.objects.filter(registered_user_id=user_id).order_by('-created_at')
            
            # If more than one request exists, keep only the most recent
            if user_requests.count() > 1:
                # Keep the first one (most recent) and delete the rest
                most_recent = user_requests.first()
                to_delete = user_requests.exclude(id=most_recent.id)
                
                self.stdout.write(f"User ID {user_id} has {to_delete.count()} duplicate requests that will be removed.")
                
                # Delete the duplicates
                duplicates_removed += to_delete.count()
                to_delete.delete()
        
        # Count after deduplication
        total_after = ApparelRequest.objects.count()
        self.stdout.write(self.style.SUCCESS(f"Deduplication complete. Removed {duplicates_removed} duplicate requests."))
        self.stdout.write(self.style.SUCCESS(f"Total apparel requests after deduplication: {total_after}"))
