import pghistory
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models

from apps.core.history import TrackedModel


@pghistory.track()
class RideCredit(TrackedModel):
    """
    Represents a user's ride credit (a ride they have ridden).
    Functions as a through-model for tracking which rides a user has experienced.
    """

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="ride_credits",
        help_text="User who rode the ride",
    )
    ride = models.ForeignKey(
        "rides.Ride",
        on_delete=models.CASCADE,
        related_name="credits",
        help_text="The ride that was ridden",
    )

    # Credit Details
    count = models.PositiveIntegerField(default=1, help_text="Number of times ridden")
    rating = models.IntegerField(
        null=True,
        blank=True,
        validators=[MinValueValidator(1), MaxValueValidator(5)],
        help_text="Personal rating (1-5)",
    )
    first_ridden_at = models.DateField(null=True, blank=True, help_text="Date of first ride")
    last_ridden_at = models.DateField(null=True, blank=True, help_text="Date of most recent ride")
    notes = models.TextField(blank=True, help_text="Personal notes about the experience")
    display_order = models.PositiveIntegerField(default=0, help_text="User-defined display order for drag-drop sorting")

    class Meta(TrackedModel.Meta):
        verbose_name = "Ride Credit"
        verbose_name_plural = "Ride Credits"
        unique_together = ["user", "ride"]
        ordering = ["display_order", "-last_ridden_at", "-first_ridden_at", "-created_at"]

    def __str__(self):
        return f"{self.user} - {self.ride}"
