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

from apps.core.choices import RichChoiceField
from apps.core.history import TrackedModel


@pghistory.track()
class UserList(TrackedModel):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="user_lists",
        help_text="User who created this list",
    )
    title = models.CharField(max_length=100, help_text="Title of the list")
    category = RichChoiceField(
        choice_group="top_list_categories",
        domain="accounts",
        max_length=2,
        help_text="Category of items in this list",
    )
    description = models.TextField(blank=True, help_text="Description of the list")
    is_public = models.BooleanField(default=True, help_text="Whether this list is visible to others")

    class Meta(TrackedModel.Meta):
        verbose_name = "User List"
        verbose_name_plural = "User Lists"
        ordering = ["-updated_at"]

    def __str__(self):
        return f"{self.user.username}'s {self.category} List: {self.title}"


@pghistory.track()
class ListItem(TrackedModel):
    user_list = models.ForeignKey(
        UserList,
        on_delete=models.CASCADE,
        related_name="items",
        help_text="List this item belongs to",
    )
    content_type = models.ForeignKey(
        ContentType,
        on_delete=models.CASCADE,
        help_text="Type of item (park, ride, etc.)",
    )
    object_id = models.PositiveIntegerField(help_text="ID of the item")
    content_object = GenericForeignKey("content_type", "object_id")
    rank = models.PositiveIntegerField(help_text="Position in the list")
    notes = models.TextField(blank=True, help_text="User's notes about this item")

    class Meta(TrackedModel.Meta):
        verbose_name = "List Item"
        verbose_name_plural = "List Items"
        ordering = ["rank"]
        unique_together = [["user_list", "rank"]]

    def __str__(self):
        return f"#{self.rank} in {self.user_list.title}"
