"""
Ride Name History model for tracking historical ride names.

This model stores the history of name changes for rides, enabling display of
former names on ride detail pages.
"""

import pghistory
from django.db import models

from apps.core.models import TrackedModel


@pghistory.track()
class RideNameHistory(TrackedModel):
    """
    Tracks historical names of rides.

    When a ride is renamed, this model stores the previous name along with
    the year range it was used and an optional reason for the change.
    """

    ride = models.ForeignKey(
        "rides.Ride",
        on_delete=models.CASCADE,
        related_name="former_names",
        help_text="The ride this name history entry belongs to",
    )
    former_name = models.CharField(
        max_length=200,
        help_text="The previous name of the ride",
    )
    from_year = models.PositiveSmallIntegerField(
        null=True,
        blank=True,
        help_text="Year the ride started using this name",
    )
    to_year = models.PositiveSmallIntegerField(
        null=True,
        blank=True,
        help_text="Year the ride stopped using this name",
    )
    reason = models.CharField(
        max_length=500,
        blank=True,
        help_text="Reason for the name change (e.g., 'Retheme to Peanuts')",
    )

    class Meta(TrackedModel.Meta):
        verbose_name = "Ride Name History"
        verbose_name_plural = "Ride Name Histories"
        ordering = ["-to_year", "-from_year"]
        indexes = [
            models.Index(fields=["ride", "-to_year"]),
        ]

    def __str__(self):
        year_range = ""
        if self.from_year and self.to_year:
            year_range = f" ({self.from_year}-{self.to_year})"
        elif self.to_year:
            year_range = f" (until {self.to_year})"
        elif self.from_year:
            year_range = f" (from {self.from_year})"
        return f"{self.former_name}{year_range}"

    def clean(self):
        from django.core.exceptions import ValidationError

        if self.from_year and self.to_year and self.from_year > self.to_year:
            raise ValidationError(
                {"from_year": "From year cannot be after to year."}
            )
