from django.db import models


class AuditLog(models.Model):
    ACTION_CHOICES = [
        ('create', 'Create'),
        ('update', 'Update'),
        ('delete', 'Delete'),
        ('status_change', 'Status Change'),
        ('assign', 'Assignment'),
        ('comment', 'Comment Added'),
        ('attachment', 'File Uploaded'),
        ('approval', 'Approval Action'),
        ('escalation', 'Escalation'),
        ('reopen', 'Ticket Reopened'),
        ('close', 'Ticket Closed'),
        ('sla_change', 'SLA Change'),
        ('ai_reply_used', 'AI Reply Used'),
        ('ai_reply_edited', 'AI Reply Edited'),
        ('login', 'Login'),
        ('logout', 'Logout'),
        ('export', 'Data Export'),
    ]

    user = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True, blank=True)
    action = models.CharField(max_length=30, choices=ACTION_CHOICES)
    model_name = models.CharField(max_length=50)
    object_id = models.CharField(max_length=50, blank=True)
    object_repr = models.CharField(max_length=200, blank=True)
    previous_value = models.JSONField(null=True, blank=True)
    new_value = models.JSONField(null=True, blank=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    user_agent = models.TextField(blank=True)
    extra_data = models.JSONField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['model_name', 'object_id']),
            models.Index(fields=['user', 'created_at']),
        ]

    def __str__(self):
        return f"{self.action} on {self.model_name}:{self.object_id} by {self.user}"
