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


CATEGORY_CHOICES = [
    ("taarifa",   "Taarifa — Local Alert"),
    ("shughuli",  "Shughuli — Event"),
    ("biashara",  "Biashara — Business Advert"),
    ("kazi",      "Kazi — Job Listing"),
    ("matatu",    "Matatu — Transport Update"),
    ("harambee",  "Harambee — Fundraiser"),
    ("general",   "General Announcement"),
]

NEIGHBORHOOD_CHOICES = [
    ("all",          "All Thika"),
    ("makongeni",    "Makongeni"),
    ("township",     "Township"),
    ("landless",     "Landless"),
    ("kiandutu",     "Kiandutu"),
    ("gatuanyaga",   "Gatuanyaga"),
    ("thika_greens", "Thika Greens"),
    ("section_9",    "Section 9"),
    ("ngoigwa",      "Ngoigwa"),
    ("kamenu",       "Kamenu"),
]

PRIORITY_CHOICES = [
    ("normal", "Normal"),
    ("high",   "High — shown prominently"),
    ("urgent", "Urgent — red alert"),
]


class Announcement(models.Model):
    title        = models.CharField(max_length=200)
    body         = models.TextField()
    category     = models.CharField(max_length=30, choices=CATEGORY_CHOICES, default="general")
    neighborhood = models.CharField(max_length=30, choices=NEIGHBORHOOD_CHOICES, default="all")
    priority     = models.CharField(max_length=10, choices=PRIORITY_CHOICES, default="normal")
    image        = models.ImageField(upload_to="announcements/", blank=True, null=True)
    link         = models.URLField(blank=True, null=True, help_text="Optional external link")
    is_active    = models.BooleanField(default=True)
    is_broadcast = models.BooleanField(
        default=False,
        help_text="If true, this will be sent as a message to relevant chat rooms"
    )
    broadcast_done = models.BooleanField(default=False)
    created_by   = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True, related_name="announcements"
    )
    created_at   = models.DateTimeField(auto_now_add=True)
    updated_at   = models.DateTimeField(auto_now=True)
    expires_at   = models.DateTimeField(
        null=True, blank=True,
        help_text="Leave blank to never expire"
    )

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return f"[{self.get_category_display()}] {self.title}"


class AnnouncementView(models.Model):
    """Tracks which users have seen which announcements."""
    announcement = models.ForeignKey(
        Announcement, on_delete=models.CASCADE, related_name="views"
    )
    user         = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE, related_name="announcement_views"
    )
    viewed_at    = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ("announcement", "user")

    def __str__(self):
        return f"{self.user.username} saw {self.announcement.title}"