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

from apps.core.models import TimeStampedModel


class Channel(models.TextChoices):
    IN_APP = "in_app", "In-platform"
    EMAIL = "email", "Email"
    SMS = "sms", "SMS"
    WHATSAPP = "whatsapp", "WhatsApp"


class NotificationStatus(models.TextChoices):
    PENDING = "pending", "Pending"
    SENT = "sent", "Sent"
    DELIVERED = "delivered", "Delivered"
    READ = "read", "Read"
    FAILED = "failed", "Failed"


class NotificationKind(models.TextChoices):
    TRANSACTION = "transaction", "Transaction"
    MILESTONE = "milestone", "Project milestone"
    DOCUMENT = "document", "Document"
    SECURITY = "security", "Security alert"
    SUPPORT = "support", "Support"
    GENERAL = "general", "General"


class NotificationPreference(TimeStampedModel):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notification_preferences")
    email_alerts = models.BooleanField(default=True)
    sms_alerts = models.BooleanField(default=True)
    document_posted = models.BooleanField(default=True)
    login_alerts = models.BooleanField(default=False)
    whatsapp_alerts = models.BooleanField(default=False)

    def __str__(self):
        return f"Prefs · {self.user.email}"


class Notification(TimeStampedModel):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notifications")
    title = models.CharField(max_length=180)
    body = models.TextField()
    kind = models.CharField(max_length=20, choices=NotificationKind.choices, default=NotificationKind.GENERAL)
    channel = models.CharField(max_length=16, choices=Channel.choices, default=Channel.IN_APP)
    status = models.CharField(max_length=16, choices=NotificationStatus.choices, default=NotificationStatus.PENDING)
    sent_at = models.DateTimeField(null=True, blank=True)
    read_at = models.DateTimeField(null=True, blank=True)
    failed_reason = models.CharField(max_length=255, blank=True)
    project = models.ForeignKey("projects.Project", null=True, blank=True, on_delete=models.SET_NULL)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return f"{self.title} → {self.user.email}"
