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


class AuditLog(models.Model):
    class Action(models.TextChoices):
        CREATE = "create", "Create"
        UPDATE = "update", "Update"
        DELETE = "delete", "Delete"
        APPROVE = "approve", "Approve"
        EXPORT = "export", "Export"
        PRINT = "print", "Print"
        VOID = "void", "Void"
        REVERSE = "reverse", "Reverse"
        LOGIN = "login", "Login"
        LOGOUT = "logout", "Logout"

    actor = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="audit_logs",
    )
    action = models.CharField(max_length=20, choices=Action.choices)
    app_label = models.CharField(max_length=64)
    model_name = models.CharField(max_length=128)
    object_id = models.CharField(max_length=64, blank=True)
    object_repr = models.CharField(max_length=255, blank=True)
    old_values = models.JSONField(default=dict, blank=True)
    new_values = models.JSONField(default=dict, blank=True)
    changes = models.JSONField(default=dict, blank=True)
    metadata = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ("-created_at", "-id")
        indexes = [
            models.Index(fields=["app_label", "model_name"]),
            models.Index(fields=["action", "created_at"]),
            models.Index(fields=["object_id"]),
        ]

    def __str__(self):
        return (
            f"{self.get_action_display()} | {self.app_label}.{self.model_name} "
            f"#{self.object_id or 'n/a'}"
        )
