from django.core.exceptions import ValidationError
from django.db import models
from django.template.defaultfilters import slugify
from django.utils import timezone


class Event(models.Model):
    name = models.CharField(max_length=150)
    slug = models.SlugField(max_length=180, unique=True, blank=True)
    location = models.CharField(max_length=180, blank=True)
    start = models.DateTimeField()
    end = models.DateTimeField()
    event_url = models.URLField(blank=True)
    summary = models.TextField(blank=True)
    is_published = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['start', 'name']

    def __str__(self):
        return f"{self.name} ({timezone.localtime(self.start):%b %d, %Y})"

    def clean(self):
        super().clean()
        if self.start is not None and self.end is not None and self.end <= self.start:
            raise ValidationError({'end': 'End time must be after the start time.'})

    def save(self, *args, **kwargs):
        if not self.slug:
            local_start = timezone.localtime(self.start) if timezone.is_aware(self.start) else self.start
            base_slug = slugify(f"{self.name}-{local_start:%Y-%m-%d}")[:170] or 'event'
            slug = base_slug
            index = 2
            while Event.objects.exclude(pk=self.pk).filter(slug=slug).exists():
                slug = f"{base_slug[:165]}-{index}"
                index += 1
            self.slug = slug
        super().save(*args, **kwargs)
