from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand

from apps.parks.models import Park, ParkPhoto, ParkReview
from apps.rides.models import Ride, RidePhoto

User = get_user_model()


class Command(BaseCommand):
    help = "Cleans up test users and data created during e2e testing"

    def handle(self, *args, **kwargs):
        # Delete test users
        test_users = User.objects.filter(username__in=["testuser", "moderator"])
        count = test_users.count()
        test_users.delete()
        self.stdout.write(self.style.SUCCESS(f"Deleted {count} test users"))

        # Delete test reviews
        reviews = ParkReview.objects.filter(user__username__in=["testuser", "moderator"])
        count = reviews.count()
        reviews.delete()
        self.stdout.write(self.style.SUCCESS(f"Deleted {count} test reviews"))

        # Delete test photos - both park and ride photos
        park_photos = ParkPhoto.objects.filter(uploader__username__in=["testuser", "moderator"])
        park_count = park_photos.count()
        park_photos.delete()
        self.stdout.write(self.style.SUCCESS(f"Deleted {park_count} test park photos"))

        ride_photos = RidePhoto.objects.filter(uploader__username__in=["testuser", "moderator"])
        ride_count = ride_photos.count()
        ride_photos.delete()
        self.stdout.write(self.style.SUCCESS(f"Deleted {ride_count} test ride photos"))

        # Delete test parks
        parks = Park.objects.filter(name__startswith="Test Park")
        count = parks.count()
        parks.delete()
        self.stdout.write(self.style.SUCCESS(f"Deleted {count} test parks"))

        # Delete test rides
        rides = Ride.objects.filter(name__startswith="Test Ride")
        count = rides.count()
        rides.delete()
        self.stdout.write(self.style.SUCCESS(f"Deleted {count} test rides"))

        # Clean up test files
        import glob
        import os

        # Clean up test uploads
        media_patterns = [
            "media/uploads/test_*",
            "media/avatars/test_*",
            "media/park/test_*",
            "media/rides/test_*",
        ]

        for pattern in media_patterns:
            files = glob.glob(pattern)
            for f in files:
                try:
                    os.remove(f)
                    self.stdout.write(self.style.SUCCESS(f"Deleted {f}"))
                except OSError as e:
                    self.stdout.write(self.style.WARNING(f"Error deleting {f}: {e}"))

        self.stdout.write(self.style.SUCCESS("Test data cleanup complete"))
