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


class NotificationType(models.TextChoices):
    PRICE_OUT_OF_RANGE = 'PRICE_OUT_OF_RANGE', 'Sale priced outside normal range'
    OUT_OF_STOCK = 'OUT_OF_STOCK', 'Part out of stock'
    LOW_STOCK = 'LOW_STOCK', 'Part low on stock'


class NotificationSetting(models.Model):
    """Which roles receive which notification types. A manager-editable matrix."""

    role = models.CharField(max_length=20)
    notification_type = models.CharField(max_length=30, choices=NotificationType.choices)
    enabled = models.BooleanField(default=True)

    class Meta:
        unique_together = ('role', 'notification_type')
        ordering = ['notification_type', 'role']

    def __str__(self):
        return f'{self.role} / {self.notification_type}: {"on" if self.enabled else "off"}'


class Notification(models.Model):
    recipient = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='notifications',
    )
    notification_type = models.CharField(max_length=30, choices=NotificationType.choices)
    title = models.CharField(max_length=200)
    message = models.CharField(max_length=500, blank=True)
    link_path = models.CharField(max_length=200, blank=True)
    is_read = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['recipient', 'is_read']),
        ]

    def __str__(self):
        return f'{self.recipient}: {self.title}'
