import pghistory
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models

# Using string reference for CloudflareImage to avoid circular imports if possible,
# or direct import if safe. django-cloudflare-images-toolkit usually provides a field or model.
# Checking installed apps... it's "django_cloudflareimages_toolkit".
from django_cloudflareimages_toolkit.models import CloudflareImage

from apps.core.history import TrackedModel


@pghistory.track()
class Photo(TrackedModel):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="photos",
        help_text="User who uploaded this photo",
    )

    # The actual image
    image = models.ForeignKey(
        CloudflareImage, on_delete=models.CASCADE, related_name="photos_usage", help_text="Cloudflare Image reference"
    )

    # Generic relation to target object (Park, Ride, etc.)
    content_type = models.ForeignKey(
        ContentType,
        on_delete=models.CASCADE,
        help_text="Type of item this photo belongs to",
    )
    object_id = models.PositiveIntegerField(help_text="ID of the item")
    content_object = GenericForeignKey("content_type", "object_id")

    # Metadata
    caption = models.CharField(max_length=255, blank=True, help_text="Photo caption")
    is_public = models.BooleanField(default=True, help_text="Whether this photo is visible to others")

    # We might want credit/source info if not taken by user
    source = models.CharField(max_length=100, blank=True, help_text="Source/Credit if applicable")

    class Meta(TrackedModel.Meta):
        verbose_name = "Photo"
        verbose_name_plural = "Photos"
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["content_type", "object_id"]),
        ]

    def __str__(self):
        return f"Photo by {self.user.username} for {self.content_object}"
