from django.db import models
from django.contrib.contenttypes.fields import GenericRelation
from django.utils.text import slugify
from simple_history.models import HistoricalRecords

class Company(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique=True)
    headquarters = models.CharField(max_length=255, blank=True)
    description = models.TextField(blank=True)
    website = models.URLField(blank=True)
    founded_date = models.DateField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    photos = GenericRelation('media.Photo')
    history = HistoricalRecords()
    
    # Stats fields
    total_parks = models.PositiveIntegerField(default=0)
    total_rides = models.PositiveIntegerField(default=0)

    class Meta:
        verbose_name_plural = "companies"
        ordering = ['name']

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super().save(*args, **kwargs)

    @classmethod
    def get_by_slug(cls, slug):
        """Get company by current or historical slug"""
        try:
            return cls.objects.get(slug=slug), False
        except cls.DoesNotExist:
            # Check historical slugs
            history = cls.history.filter(slug=slug).order_by('-history_date').first()
            if history:
                return cls.objects.get(id=history.id), True
            raise cls.DoesNotExist("No company found with this slug")

class Manufacturer(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique=True)
    headquarters = models.CharField(max_length=255, blank=True)
    description = models.TextField(blank=True)
    website = models.URLField(blank=True)
    founded_date = models.DateField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    photos = GenericRelation('media.Photo')
    history = HistoricalRecords()
    
    # Stats fields
    total_rides = models.PositiveIntegerField(default=0)
    total_roller_coasters = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super().save(*args, **kwargs)

    @classmethod
    def get_by_slug(cls, slug):
        """Get manufacturer by current or historical slug"""
        try:
            return cls.objects.get(slug=slug), False
        except cls.DoesNotExist:
            # Check historical slugs
            history = cls.history.filter(slug=slug).order_by('-history_date').first()
            if history:
                return cls.objects.get(id=history.id), True
            raise cls.DoesNotExist("No manufacturer found with this slug")
