from __future__ import annotations

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

from apps.core.ids import uuid7
from apps.core.models import UUIDModel


class Notification(UUIDModel):
    recipient = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notifications")
    agency = models.ForeignKey("agencies.Agency", null=True, blank=True, on_delete=models.CASCADE, related_name="notifications")
    notification_type = models.CharField(max_length=32, default="INFO")
    priority = models.CharField(max_length=10, default="NORMAL", choices=[("LOW", "Basse"), ("NORMAL", "Normale"), ("HIGH", "Haute")])
    title = models.CharField(max_length=180)
    body = models.TextField(blank=True)
    action_url = models.CharField(max_length=255, blank=True)
    read_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(default=timezone.now, db_index=True)

    class Meta:
        verbose_name = "notification"
        ordering = ["-created_at"]


class Announcement(UUIDModel):
    scope = models.CharField(max_length=10, default="AGENCY", choices=[("NATIONAL", "National"), ("AGENCY", "Agence")])
    agency = models.ForeignKey("agencies.Agency", null=True, blank=True, on_delete=models.CASCADE, related_name="announcements")
    title = models.CharField(max_length=180)
    body = models.TextField()
    starts_at = models.DateTimeField(default=timezone.now)
    ends_at = models.DateTimeField(null=True, blank=True)
    status = models.CharField(max_length=10, default="PUBLISHED", choices=[("DRAFT", "Brouillon"), ("PUBLISHED", "Publiée"), ("ARCHIVED", "Archivée")])
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name="+")
    created_at = models.DateTimeField(default=timezone.now)

    class Meta:
        verbose_name = "annonce"
        ordering = ["-starts_at"]
        permissions = [("publish_announcement", "Peut publier une annonce locale"),
                       ("publish_national_announcement", "Peut publier une annonce nationale")]

    def __str__(self):
        return self.title

    @property
    def is_live(self):
        now = timezone.now()
        return self.status == "PUBLISHED" and self.starts_at <= now and (self.ends_at is None or self.ends_at >= now)
