"""
Tests for park models functionality including CRUD operations,
slug handling, status management, and location integration.
"""

from django.db import IntegrityError
from django.test import TestCase

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

# NOTE: These tests need to be updated to work with the new ParkLocation model
# instead of the generic Location model


class ParkModelTests(TestCase):
    def setUp(self):
        """Set up test data"""
        self.operator = Company.objects.create(name="Test Company", slug="test-company")

        # Create a basic park
        self.park = Park.objects.create(
            name="Test Park",
            description="A test park",
            status="OPERATING",
            operator=self.operator,
        )

        # Create location for the park
        self.location = ParkLocation.objects.create(
            park=self.park,
            street_address="123 Test St",
            city="Test City",
            state="Test State",
            country="Test Country",
            postal_code="12345",
        )
        self.location.set_coordinates(40.7128, -74.0060)
        self.location.save()

    def test_park_creation(self):
        """Test basic park creation and fields"""
        self.assertEqual(self.park.name, "Test Park")
        self.assertEqual(self.park.slug, "test-park")
        self.assertEqual(self.park.status, "OPERATING")
        self.assertEqual(self.park.operator, self.operator)

    def test_slug_generation(self):
        """Test automatic slug generation"""
        park = Park.objects.create(
            name="Another Test Park",
            status="OPERATING",
            operator=self.operator,
        )
        self.assertEqual(park.slug, "another-test-park")

    def test_historical_slug_lookup(self):
        """Test finding park by historical slug"""
        from core.history import HistoricalSlug
        from django.contrib.contenttypes.models import ContentType
        from django.db import transaction

        with transaction.atomic():
            # Create initial park with a specific name/slug
            park = Park.objects.create(
                name="Original Park Name",
                description="Test description",
                status="OPERATING",
                operator=self.operator,
            )
            original_slug = park.slug
            print(f"\nInitial park created with slug: {original_slug}")

            # Ensure we have a save to trigger history
            park.save()

            # Modify name to trigger slug change
            park.name = "Updated Park Name"
            park.save()
            new_slug = park.slug
            print(f"Park updated with new slug: {new_slug}")

            # Check HistoricalSlug records
            historical_slugs = HistoricalSlug.objects.filter(
                content_type=ContentType.objects.get_for_model(Park),
                object_id=park.id,
            )
            print(f"Historical slug records: {[h.slug for h in historical_slugs]}")

            # Check pghistory records
            event_model = getattr(Park, "event_model", None)
            if event_model:
                historical_records = event_model.objects.filter(pgh_obj_id=park.id).order_by("-pgh_created_at")
                print("\nPG History records:")
                for record in historical_records:
                    print(f"- Event ID: {record.pgh_id}")
                    print(f"  Name: {record.name}")
                    print(f"  Slug: {record.slug}")
                    print(f"  Created At: {record.pgh_created_at}")
            else:
                print("\nNo pghistory event model available")

            # Try to find by old slug
            found_park, is_historical = Park.get_by_slug(original_slug)
            self.assertEqual(found_park.id, park.id)
            print(f"Found park by old slug: {found_park.slug}, is_historical: {is_historical}")
            self.assertTrue(is_historical)

            # Try current slug
            found_park, is_historical = Park.get_by_slug(new_slug)
            self.assertEqual(found_park.id, park.id)
            print(f"Found park by new slug: {found_park.slug}, is_historical: {is_historical}")
            self.assertFalse(is_historical)

    def test_status_color_mapping(self):
        """Test status color class mapping"""
        status_tests = {
            "OPERATING": "bg-green-100 text-green-800",
            "CLOSED_TEMP": "bg-yellow-100 text-yellow-800",
            "CLOSED_PERM": "bg-red-100 text-red-800",
            "UNDER_CONSTRUCTION": "bg-blue-100 text-blue-800",
            "DEMOLISHED": "bg-gray-100 text-gray-800",
            "RELOCATED": "bg-purple-100 text-purple-800",
        }

        for status, expected_color in status_tests.items():
            self.park.status = status
            self.assertEqual(self.park.get_status_color(), expected_color)

    def test_absolute_url(self):
        """Test get_absolute_url method"""
        expected_url = f"/parks/{self.park.slug}/"
        self.assertEqual(self.park.get_absolute_url(), expected_url)


class ParkAreaModelTests(TestCase):
    def setUp(self):
        """Set up test data"""
        self.operator = Company.objects.create(name="Test Company 2", slug="test-company-2")
        self.park = Park.objects.create(name="Test Park", status="OPERATING", operator=self.operator)
        self.area = ParkArea.objects.create(park=self.park, name="Test Area", description="A test area")

    def test_area_creation(self):
        """Test basic area creation and fields"""
        self.assertEqual(self.area.name, "Test Area")
        self.assertEqual(self.area.slug, "test-area")
        self.assertEqual(self.area.park, self.park)

    def test_unique_together_constraint(self):
        """Test unique_together constraint for park and slug"""
        from django.db import transaction

        # Try to create area with same slug in same park
        with transaction.atomic(), self.assertRaises(IntegrityError):
            ParkArea.objects.create(
                park=self.park,
                name="Test Area",  # Will generate same slug
            )

        # Should be able to use same name in different park
        other_park = Park.objects.create(name="Other Park", operator=self.operator)
        area = ParkArea.objects.create(park=other_park, name="Test Area")
        self.assertEqual(area.slug, "test-area")
