from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

from apps.common.models import BaseModel

# Create your models here.


class Notification(BaseModel):
    """
    Model for storing user notifications.
    
    This model provides a centralized notification system
    for sending messages and alerts to users.
    
    Attributes:
        recipient (ForeignKey): User who should receive the notification
        title (CharField): Notification title
        message (TextField): Notification message
        notification_type (CharField): Type of notification
        is_read (BooleanField): Whether notification has been read
        read_at (DateTimeField): When notification was read
        action_url (URLField): Optional URL for notification action
    """
    
    NOTIFICATION_TYPES = [
        ('info', _('Information')),
        ('success', _('Success')),
        ('warning', _('Warning')),
        ('error', _('Error')),
        ('system', _('System')),
    ]
    
    recipient = models.ForeignKey(
        'accounts.User',
        on_delete=models.CASCADE,
        related_name='notifications',
        verbose_name=_('Recipient'),
        help_text=_('User who should receive this notification')
    )
    title = models.CharField(
        _('Title'),
        max_length=200,
        help_text=_('Notification title')
    )
    message = models.TextField(
        _('Message'),
        help_text=_('Notification message content')
    )
    notification_type = models.CharField(
        _('Type'),
        max_length=20,
        choices=NOTIFICATION_TYPES,
        default='info',
        help_text=_('Type of notification')
    )
    is_read = models.BooleanField(
        _('Is Read'),
        default=False,
        help_text=_('Whether this notification has been read')
    )
    read_at = models.DateTimeField(
        _('Read At'),
        null=True,
        blank=True,
        help_text=_('When this notification was read')
    )
    action_url = models.URLField(
        _('Action URL'),
        blank=True,
        help_text=_('Optional URL for notification action')
    )
    
    class Meta:
        verbose_name = _('Notification')
        verbose_name_plural = _('Notifications')
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['recipient', 'is_read']),
            models.Index(fields=['notification_type', 'created_at']),
        ]
    
    def __str__(self):
        return f"{self.title} - {self.recipient.username}"
    
    def mark_as_read(self):
        """Mark the notification as read."""
        if not self.is_read:
            self.is_read = True
            self.read_at = timezone.now()
            self.save(update_fields=['is_read', 'read_at'])