import pghistory
import pytest
from django.contrib.auth import get_user_model

from apps.parks.models import Company, Park

User = get_user_model()


@pytest.mark.django_db
class TestTrackedModel:
    """
    Tests for the TrackedModel base class and pghistory integration.
    """

    def test_create_history_tracking(self):
        """Test that creating a model instance creates a history event."""
        user = User.objects.create_user(username="testuser", password="password")
        company = Company.objects.create(name="Test Operator", roles=["OPERATOR"])

        with pghistory.context(user=user.id):
            park = Park.objects.create(
                name="History Test Park", description="Testing history", operating_season="Summer", operator=company
            )

        # Verify history using the helper method from TrackedModel
        events = park.get_history()
        assert events.count() == 1
        event = events.first()
        assert event.pgh_obj_id == park.pk

        # Verify context was captured
        # The middleware isn't running here, so we used pghistory.context explicitly
        # But pghistory.context stores data in pgh_context field if configured?
        # Let's check if the event has pgh_context
        assert event.pgh_context["user"] == user.id

    def test_update_tracking(self):
        company = Company.objects.create(name="Test Operator 2", roles=["OPERATOR"])
        park = Park.objects.create(name="Original", operator=company)

        # Initial create event
        assert park.get_history().count() == 1

        # Update
        park.name = "Updated"
        park.save()

        assert park.get_history().count() == 2
        latest = park.get_history().first()  # Ordered by -pgh_created_at
        assert latest.name == "Updated"
