from django.conf import settings
from django.db import models
from django.utils import timezone

User = settings.AUTH_USER_MODEL

class Announcement(models.Model):
    title = models.CharField(max_length=200, blank=True)
    message = models.TextField()
    is_active = models.BooleanField(default=True)
    start_at = models.DateTimeField(default=timezone.now)
    end_at = models.DateTimeField(null=True, blank=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='announcements_created')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return self.title or f"Announcement #{self.pk}"

    def is_current(self):
        return bool(self.is_active)


class AnnouncementDismissal(models.Model):
    announcement = models.ForeignKey(Announcement, on_delete=models.CASCADE)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    dismissed_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('announcement', 'user')
        indexes = [
            models.Index(fields=['user']),
            models.Index(fields=['announcement']),
        ]

    def __str__(self):
        return f"Dismissal(u={self.user_id}, a={self.announcement_id})"