from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from smoothschedule.identity.users.models import User

class Notification(models.Model):
    """
    Generic notification model for in-app user notifications.
    Uses Django's GenericForeignKey to link to any object that triggers the notification.
    """
    recipient = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='notifications',
        help_text="The user who should receive this notification."
    )
    actor_content_type = models.ForeignKey(
        ContentType,
        on_delete=models.CASCADE,
        related_name='notifications_as_actor',
        null=True, blank=True
    )
    actor_object_id = models.CharField(max_length=255, null=True, blank=True)
    actor = GenericForeignKey('actor_content_type', 'actor_object_id')
    
    verb = models.CharField(
        max_length=255,
        help_text="A short phrase describing the action (e.g., 'assigned you to a ticket', 'commented on your ticket')."
    )

    action_object_content_type = models.ForeignKey(
        ContentType,
        on_delete=models.CASCADE,
        related_name='notifications_as_action_object',
        null=True, blank=True
    )
    action_object_object_id = models.CharField(max_length=255, null=True, blank=True)
    action_object = GenericForeignKey('action_object_content_type', 'action_object_object_id')

    target_content_type = models.ForeignKey(
        ContentType,
        on_delete=models.CASCADE,
        related_name='notifications_as_target',
        null=True, blank=True
    )
    target_object_id = models.CharField(max_length=255, null=True, blank=True)
    target = GenericForeignKey('target_content_type', 'target_object_id')

    read = models.BooleanField(default=False, help_text="Whether the recipient has read this notification.")
    timestamp = models.DateTimeField(auto_now_add=True)
    
    data = models.JSONField(
        default=dict,
        blank=True,
        help_text="Optional JSON data for extra context, e.g., links, previous values."
    )

    class Meta:
        app_label = 'notifications'
        ordering = ['-timestamp']
        indexes = [
            models.Index(fields=['recipient', 'read', 'timestamp']),
            models.Index(fields=['recipient', 'timestamp']),
        ]

    def __str__(self):
        return f"{self.recipient.email} - {self.verb} - {self.timestamp.strftime('%Y-%m-%d %H:%M')}"