from django.core.management.base import BaseCommand

from apps.parks.models import Company, Park, ParkLocation


class Command(BaseCommand):
    help = "Test ParkLocation model functionality"

    def handle(self, *args, **options):
        self.stdout.write("🧪 Testing ParkLocation Model Functionality")
        self.stdout.write("=" * 50)

        # Create a test company (operator)
        operator, created = Company.objects.get_or_create(
            name="Test Theme Parks Inc",
            defaults={"slug": "test-theme-parks-inc", "roles": ["OPERATOR"]},
        )
        self.stdout.write(f"✅ Created operator: {operator.name}")

        # Create a test park
        park, created = Park.objects.get_or_create(
            name="Test Magic Kingdom",
            defaults={
                "slug": "test-magic-kingdom",
                "description": "A test theme park for location testing",
                "operator": operator,
            },
        )
        self.stdout.write(f"✅ Created park: {park.name}")

        # Create a park location
        location, created = ParkLocation.objects.get_or_create(
            park=park,
            defaults={
                "street_address": "1313 Disneyland Dr",
                "city": "Anaheim",
                "state": "California",
                "country": "USA",
                "postal_code": "92802",
                "highway_exit": "I-5 Exit 110B",
                "parking_notes": "Large parking structure available",
                "seasonal_notes": "Open year-round",
            },
        )
        self.stdout.write(f"✅ Created location: {location}")

        # Test coordinate setting
        self.stdout.write("\n🔍 Testing coordinate functionality:")
        location.set_coordinates(33.8121, -117.9190)  # Disneyland coordinates
        location.save()

        self.stdout.write(f"  Latitude: {location.latitude}")
        self.stdout.write(f"  Longitude: {location.longitude}")
        self.stdout.write(f"  Coordinates: {location.coordinates}")
        self.stdout.write(f"  Formatted Address: {location.formatted_address}")

        # Test Park model integration
        self.stdout.write("\n🔍 Testing Park model integration:")
        self.stdout.write(f"  Park formatted location: {park.formatted_location}")
        self.stdout.write(f"  Park coordinates: {park.coordinates}")

        # Create another location for distance testing
        operator2, created = Company.objects.get_or_create(
            name="Six Flags Entertainment",
            defaults={
                "slug": "six-flags-entertainment",
                "roles": ["OPERATOR"],
            },
        )

        park2, created = Park.objects.get_or_create(
            name="Six Flags Magic Mountain",
            defaults={
                "slug": "six-flags-magic-mountain",
                "description": "Another test theme park",
                "operator": operator2,
            },
        )

        location2, created = ParkLocation.objects.get_or_create(
            park=park2,
            defaults={
                "city": "Valencia",
                "state": "California",
                "country": "USA",
            },
        )
        location2.set_coordinates(34.4244, -118.5971)  # Six Flags Magic Mountain coordinates
        location2.save()

        # Test distance calculation
        self.stdout.write("\n🔍 Testing distance calculation:")
        distance = location.distance_to(location2)
        if distance:
            self.stdout.write(f"  Distance between parks: {distance:.2f} km")
        else:
            self.stdout.write("  ❌ Distance calculation failed")

        # Test spatial indexing
        self.stdout.write("\n🔍 Testing spatial queries:")
        try:
            from django.contrib.gis.geos import Point
            from django.contrib.gis.measure import D

            # Find parks within 100km of a point
            # Same as Disneyland
            search_point = Point(-117.9190, 33.8121, srid=4326)
            nearby_locations = ParkLocation.objects.filter(point__distance_lte=(search_point, D(km=100)))
            self.stdout.write(f"  Found {nearby_locations.count()} parks within 100km")
            for loc in nearby_locations:
                self.stdout.write(f"    - {loc.park.name} in {loc.city}, {loc.state}")
        except Exception as e:
            self.stdout.write(f"  ⚠️  Spatial queries not fully functional: {e}")

        self.stdout.write("\n✅ ParkLocation model tests completed successfully!")
